Do you understand several injection methods of spring beans

Time:2020-5-15

Spring injection can be divided into three types: XML injection, annotation injection, and beandefinition injection. In terms of usage, they can be divided into three types, but the underlying implementation code is the unified beanfactory. These three types are also related to XML injection and annotation injection, which are all interfaces that rely on beandefinition extension. Annotation also transits from XML. Let’s take a brief look at these three kinds of writing methods.

XML injection

Before the spring boot framework came out, XML configuration was widely used, and the configuration process was cumbersome, but it was less intrusive to the code, and the configuration and code separation operations.

Entity definition

Define two attribute ID and name, implement get / set method, rewrite toString method, and view printing results conveniently.


public class UserXml {
  private String id;
  private String name;

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  @Override
  public String toString() {
    return "User{" 
        "id='"  id  '\'' 
        ", name='"  name  '\'' 
        '}';
  }
}

XML definition

Create a new directory under resources meta-inf and create spring- bean.xml File, and fill in the corresponding bean configuration. The bean needs to configure the ID or name value. The IOC container is unique. Class configures the defined entity path, and the corresponding property sets the initialization property.

<?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
    https://www.springframework.org/schema/beans/spring-beans.xsd">
  <bean>
    <property name="id" value="11"/>
    < property name = "name" value = "Java circle" / >
  </bean>
</beans>

output

Create a beanfactory object and instantiate it with classpathxmlapplicationcontext. Simply speaking, beanfactory is the underlying foundation of the IOC container. It can be said that the IOC container is beanfactory, and classpathxmlapplicationcontext is the function extension of the IOC container. Classpathxmlapplicationcontext needs to pass in the path of the asset file. Get the specific entity class through the getBean method, Is the result output.

//XML injection
    BeanFactory classPathXmlApplicationContext = new ClassPathXmlApplicationContext("classpath:/META-INF/spring-bean.xml");
    UserXml userXml = classPathXmlApplicationContext.getBean(UserXml.class);
    System. Out. Println ("userxml XML injection object:" userxml ");

Annotation injection

Annotation came into being after spring 2.0.3, and a large number of applications were also popular with spring boot, so we slowly accepted it. Its main advantage is simple operation. Through simple annotation, it can be identified as bean components, and it extends various levels of annotations, such as @ service, @ service, @ repository, which are derived from @ Component annotation.

Entity definition

Entities are similar to XML entities. Here, create a new class to distinguish different bean implementation methods.


public class UserAnnotation {
  private String id;
  private String name;

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  @Override
  public String toString() {
    return "User{" 
        "id='"  id  '\'' 
        ", name='"  name  '\'' 
        '}';
  }

Annotation configuration

Under normal circumstances, we scan and inject through the standard annotation @ configuration. We can directly configure the class here, instantiate the bean component in this class, and initialize it.

@Configuration
public class UserConfiguration {
  @Bean
  public UserAnnotation userAnnotation(){
    UserAnnotation userAnnotation = new UserAnnotation();
    userAnnotation.setId("11");
    Userannotation.setname ("Java circle");
    return userAnnotation;
  }
}

output

Annotationconfigpplicationcontext is also an implementation of beanfactory. It is similar to classpathxmlapplicationcontext in function, except that the loading channel is different. Register the defined configuration class to the IOC container and call the register method. Here, we need to note that the next step is to adjust the refresh method to load the bean, and then get the specific entity through getBean and output the bean.

//Annotation injection
    AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
    annotationConfigApplicationContext.register(UserConfiguration.class);
    annotationConfigApplicationContext.refresh();
    UserAnnotation userAnnotation = annotationConfigApplicationContext.getBean(UserAnnotation.class);
    System.out.println ("userannotation annotation annotation injection" userannotation);

Beandefinition injection

Beandefinition is the underlying implementation of beanfactory, including the methods mentioned above. The underlying implementation is also based on beandefinition. A bean component corresponds to a beandefinition, but it will not be used in the actual operation process, just for reference.

Entity definition

Entities are similar to XML entities. Here, create a new class to distinguish different bean implementation methods.


public class UserBeanDefinition {
  private String id;
  private String name;

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  @Override
  public String toString() {
    return "User{" 
        "id='"  id  '\'' 
        ", name='"  name  '\'' 
        '}';
  }
}

output

Instantiate a constructor through the genericbeandefinition of beandefinitionbuilder. The parameter passed in is the entity class. After the construction, do the initialization operation, and then beandefinition declaration calls the getbeandefinition method, and return to the specific parameters of the bean through getpropertyvalues to finish the output.

//Beandefinition injection
    BeanDefinitionBuilder definitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(UserBeanDefinition.class);
    definitionBuilder.addPropertyValue("id", "11");
    Definitionbuilder. Addpropertyvalue ("name", "Java circle");
    BeanDefinition beanDefinition = definitionBuilder.getBeanDefinition();
    String beanClassName = beanDefinition.getBeanClassName();
    MutablePropertyValues mutablePropertyValues = beanDefinition.getPropertyValues();
    String id = mutablePropertyValues.getPropertyValue("id").getValue().toString();
    String name = mutablePropertyValues.getPropertyValue("name").getValue().toString();
    System. Out. Println ("beandefinition injection object userbeandefinition {id =" Id ", name =" name "}");

Result output

The output results are respectively XML injection, annotation injection and bean definition injection.

Userxml XML injection object: user {id ='11 ', name ='java circle'}
Userannotation annotation injection user {id ='11 ', name ='java circle'}
Beandefinition injection object userbeandefinition {id = 11, name = Java circle}

Source code: https://github.com/itrickzhang/spring-demo

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.