The warehouse address
w4ngzhen/springboot-simple-guide: This is a project that guides SpringBoot users to get started quickly through a series of examples (github.com)
Chapter01- How to Declare beans with the Spring Framework
preface
In the previous chapter, we learned the most basic ways to use Spring:
- Through the use of
@Component
Annotations mark our class as a Bean component. - Use the Spring context object to get the Bean component from the IOC container.
In this chapter, we’ll take a closer look at three ways to declare beans using the Spring framework:
@Component
annotations- XML configuration declaration
- Java class configuration declaration (
@Configuration
)
PS: There are more than three ways that Spring can declare beans.
The use of@Component
annotations
The @Component annotation is already familiar, but it needs to be mentioned briefly. Create class Apple:
// We use the @Component annotation, and we also define the name of the Bean
@Component("myApple")
public class Apple {
public Apple(a) {
System.out.println("Apple no-argument constructor"); }}Copy the code
Get and print:
@SpringBootApplication
public class Chapter01App {
public static void main(String[] args) {
ConfigurableApplicationContext context =
SpringApplication.run(Chapter01App.class, args);
// Notice BeanName we filled in "myApple", corresponding to @Component("myApple")
Object myApple = context.getBean("myApple"); System.out.println(myApple); }}Copy the code
Java class configuration declaration
A Java class configuration declaration means that we use some Java as the Spring configuration and define beans through Java code itself. The benefits of this will be discussed later.
Start by writing our Bean class:
/** * Banana, no annotations */
public class Banana {
public Banana(a) {
System.out.println("Banana no-argument constructor"); }}Copy the code
Then, we write a Configuration class that features an annotation @Configuration on the class:
@Configuration // Add annotations to indicate that it is a Spring configuration class
public class Chapter01Configuration {
@Bean // Use '@bean' to declare a Bean
public Banana myBanana(a) { // The method name is the Bean name
System.out.println("Go into Banana Bean and create a function.");
return newBanana(); }}Copy the code
Finally, we add injection on the startup class to indicate that the configuration class is scanned:
@SpringBootApplication
// The '@import' annotation is used to specify the configuration class we need
// By default, the Configuration of the current boot class package and its subpackages are automatically scanned.
// No need to specify, this is mainly for demonstration
@Import(Chapter01Configuration.class)
public class Chapter01App {
public static void main(String[] args) {
ConfigurableApplicationContext context =
SpringApplication.run(Chapter01App.class, args);
Object myBanana = context.getBean("myBanana"); System.out.println(myBanana); }}Copy the code
In this example, the readers may be a bit more convoluted, here is to sort out the following ideas.
First, we created a plain Vanilla Java class Banana, for which we didn’t use anything about the Spring framework.
Second, we created a configuration class Chapter01Configuration. As we know from the class name, Spring has no restrictions on the name of the configuration class, as long as it is legal. The only connection to the Spring framework is the use of the @Configuration annotation, which means we mark this class as a Spring Configuration class.
So what does a configuration class do? That’s what we did in step 3: we wrote a method in the configuration class public Banana myBanana(); With the @bean annotation on its method, we define a Bean. The name of the Bean is the method name “myBanana”, and the type of the Bean is Banana.
XML Configuration Declaration Beans (Optional)
Remember above that we declared our beans in the form of annotations? In fact, the initial Spring IOC container initialization is done through configuration files, although Spring and SpringBoot projects are now mostly using annotations and Java class configuration, but the use of XML configuration, I also want you to understand.
To start, we still create a normal Java class (Coconut) :
public class Coconut {
/** * Define the field: weight, which can be obtained and set through the getter and setter below */
private int weight;
public Coconut(a) {
System.out.println("Coconut no-parameter constructor");
}
public int getWeight(a) {
return weight;
}
public void setWeight(int weight) {
this.weight = weight; }}Copy the code
As you can see from this class, we didn’t use any spring-related annotations (especially the @Component annotation), but notice that we added a little bit to this class by adding a field weight to record the weight of Coconut. How does the Spring IOC container initialize our Coconut instance? Just two steps:
- Create an XML file in which the beans are defined using the format agreed upon by the Spring framework
- On the startup class, specify that the Spring framework loads the XML
** First let’s look at step 1, creating the XML file. / SRC /main/resources/chapter01_03_use_xml_beans.xml/chapter01_03_use_xml_beans.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
Copy the code
PS: When using IDEA, it can be stored in the relevant folderRight-click - New - XML Configuration File - Spring Config
To quickly create XML with initial content.
You can see the root node
of the original XML content and guess that we can add child nodes
to it. OK, let’s define our bean:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<! MyCoconut --> defines a Bean named myCoconut -->
<bean name="myCoconut" class="com.compilemind.guide.chapter01._03_use_xml.Coconut">
<! -- For Coconut weight we set its initial value to 100 -->
<property name="weight" value="100"/>
</bean>
</beans>
Copy the code
Actually, with XML, I don’t think anything needs to be said. We first define our bean using the node
, specifying its name and the class by which it was created. We also define the initial value of Coconut weight in its child
We have now configured our beans through XML. How do we get the Spring framework to recognize and initialize our Bean? It’s easy to use @importResource to configure which XML we want to load:
@SpringBootApplication
// The '@importResource' annotation is used to load the XML configuration we specified
@ImportResource("classpath:chapter01_03_use_xml_beans.xml")
public class Chapter01App {
public static void main(String[] args) {
ConfigurableApplicationContext context =
SpringApplication.run(Chapter01App.class, args);
Object myCoconut = context.getBean("myCoconut");
if (myCoconut instanceof Coconut) {
int weight = ((Coconut) myCoconut).getWeight();
System.out.println("Coconut weight is:"+ weight); }}}Copy the code
PS:classpath:xxx
Search keywords:Spring classpath
.
The warehouse address
w4ngzhen/springboot-simple-guide: This is a project that guides SpringBoot users to get started quickly through a series of examples (github.com)