Use @Configuration and @Bean to register components in the container? Just read this one

Use @Configuration and @Bean to register components in the container?  Just read this one

 

Spring IOC 和 DI

At the bottom of the Spring container, the most important functions are IOC and DI, that is, inversion of control and dependency injection.

IOC: Inversion of control, the creation of class objects is handed over to the Spring class management creation. DI: Dependency injection, assigning values ​​to the attributes in the class during the creation of the class. The relationship between DI and IOC: DI cannot exist alone, DI needs to be completed on the basis of IOC.

Within Spring, all components are placed in the IOC container, and the relationship between components is automatically assembled through the IOC container, which is what we call dependency injection. Next, we will use annotations to complete the registration, management, dependency, and injection of container components.

Before introducing the use of annotations to complete the registration, management, dependency, and injection functions of container components, let's take a look at how to inject Beans using XML files.

Inject JavaBean through XML file

First, we create the Person class under the io.mykit.spring.bean package of the project as the JavaBean to be tested. The code is shown below.

package io.mykit.spring.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.io.Serializable;
/**
 * @author binghe
 * @version 1.0.0
 * @description 测试实体类
 */
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Person implements Serializable {
    private static final long serialVersionUID = 7387479910468805194L;
    private String name;
    private Integer age;
}

Next, we create the Spring configuration file beans.xml in the resources directory of the project, and inject the Person class into the Spring IOC container through the beans.xml file. The configuration is as follows.

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <bean id = "person" class="io.mykit.spring.bean.Person">
        <property name="name" value="binghe"></property>
        <property name="age" value="18"></property>
    </bean>
</beans>

At this point, we use XML to inject JavaBean and the configuration is complete. Next, we create a SpringBeanTest class for testing. Here, I use Junit for testing. The test method is as follows.

@Test
public void testXmlConfig(){
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    Person person = (Person) context.getBean("person");
    System.out.println(person);
}

Run the testXmlConfig() method, and the output result information is as follows.

Person(name=binghe, age=18)

From the output, we can see that the Person class has been injected into the Spring IOC container through the configuration of the beans.xml file.

Inject JavaBeans through annotations

Through XML files, we can inject JavaBeans into Spring's IOC container. How to use annotations? Don’t worry, in fact, using annotations is much simpler than using XML files. We create the PersonConfig class under the project’s io.mykit.spring.plugins.register.config package, and add the @Configuration annotation to the PersonConfig class to indicate that the PersonConfig class is A Spring configuration class that injects the Person class into Spring's IOC container through the @Bean annotation.

package io.mykit.spring.plugins.register.config;
import io.mykit.spring.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * @author binghe
 * @version 1.0.0
 * @description 以注解的形式来配置Person
 */
@Configuration
public class PersonConfig {
     @Bean
    public Person person(){        return new Person("binghe001", 18);
    }}

That's right, we can inject the Person class into Spring's IOC container through the PersonConfig class. Nice! ! Mainly we add @Configuration annotations to the class, and add @Bean annotations to the method, then the JavaBean created in the method can be injected into the Spring IOC container.

Next, we create a testAnnotationConfig() method in the SpringBeanTest class to test the Person class injected through annotations, as shown below.

@Test
public void testAnnotationConfig(){
    ApplicationContext context = new AnnotationConfigApplicationContext(PersonConfig.class);
    Person person = context.getBean(Person.class);
    System.out.println(person);}

Run the testAnnotationConfig() method, and the output result information is as follows.

Person(name=binghe001, age=18)

It can be seen that the Person class is injected into Spring's IOC container through annotations.

At this point, we have made it clear that JavaBean can be injected into Spring's IOC container through both XML files and annotations. So, when using annotations to inject JavaBeans into the IOC container, what is the name of the bean used? We can add the following code in the testAnnotationConfig() method to get the annotation name under the Person type.

//按照类型找到对应的bean名称数组
String[] names = context.getBeanNamesForType(Person.class);
Arrays.stream(names).forEach(System.out::println);

The complete code of the testAnnotationConfig() method is shown below.

@Test
public void testAnnotationConfig(){
    ApplicationContext context = new AnnotationConfigApplicationContext(PersonConfig.class);
    Person person = context.getBean(Person.class);
    System.out.println(person);    //按照类型找到对应的bean名称数组
    String[] names = context.getBeanNamesForType(Person.class);
    Arrays.stream(names).forEach(System.out::println);
}

The result information output by running the testAnnotationConfig() method is as follows.

Person(name=binghe001, age=18)
person

What is the person here? We modify the person() method in the PersonConfig class, and modify the person() method to person01(), as shown below.

package io.mykit.spring.plugins.register.config;
import io.mykit.spring.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * @author binghe
 * @version 1.0.0
 * @description 以注解的形式来配置Person
 */
@Configuration
public class PersonConfig {
    @Bean
    public Person person01(){        return new Person("binghe001", 18);
    }}

At this point, we run the testAnnotationConfig() method again, and the output result information is as follows.

Person(name=binghe001, age=18)
person01

Seeing this, everyone should have a sudden sense of enlightenment, yes! ! When using annotations to inject Javabeans, the name of the bean in the IOC is the method name marked with the @Bean annotation. Can we specify a name for the bean individually? That must be possible! Just specify the name explicitly in the @Bean annotation. For example, in the code of the PersonConfig class below, we modify the @Bean annotation on the person01() method to @Bean("person") annotation, as shown below.

package io.mykit.spring.plugins.register.config;
import io.mykit.spring.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * @author binghe
 * @version 1.0.0
 * @description 以注解的形式来配置Person
 */
@Configuration
public class PersonConfig {
    @Bean("person")
    public Person person01(){        return new Person("binghe001", 18);
    }}

At this point, we run the testAnnotationConfig() method again, and the output result information is as follows.

Person(name=binghe001, age=18)
person

As you can see, at this time, the name of the output JavaBean is person.

Conclusion: When we use annotations to inject JavaBeans into Spring's IOC container, if the bean name is not explicitly specified in the @Bean annotation, the name of the current method is used as the bean name; if it is explicitly specified in the @Bean annotation If the name of the bean is included, the name specified in the @Bean annotation is used as the name of the bean.

Okay, let's stop here today! Don’t forget to watch and forward to others, let more people see, learn together and make progress together! !

 

Guess you like

Origin blog.csdn.net/qq_45401061/article/details/108740655