SpringBoot -- container function

SpringBoot -- container function

1. Component addition

First, create two bean s, one called User and the other called Food.

Previously, in SSM, component and attribute injection needed to be set in the Configuration file. The whole process can now be implemented in full code using SpringBoot. Create a Configuration class, mark it with @ Configuration annotation, and declare the class as a Configuration class.

/*
 Declare that this class is a configuration class. Complete the configuration file in it. In this case, the configuration class is also a component of the project
 After output, it is found that it is a dynamic proxy CGLIB enhanced component object
 Configuration The annotation provides a method proxyBeanMethods [proxy component method], and its default value is true
 If it is true, the objects obtained by calling the configuration class component and then calling the configuration method in the project are the same, that is, the proxy object calls the method
 SpringBoot Always check whether there is this component in the container. If there is, take it out to you, so it has always been one. Keep component single instance          Full mode
 If it is modified to false, the objects obtained by configuring class components to call methods are not the same              Lite mode
 */
@Configuration(proxyBeanMethods = true)
public class MyConfig {
​
/*
    The Bean tag is used to identify the configuration class method. The return value is the component type, the method name is the component id, and the specific content returned is the object saved by the component in the container.
    If you want to set other component names, you can set the value attribute value in the Bean annotation
 */
    @Bean
    public User user01(){
        return new User("hanfu","woman","123456");
    }
​
    @Bean
    public Food beef(){
        return new Food("beef","99");
    }
​
}

Then go to the main program class MyApplication and use the returned run object to call the getBean method to obtain the components in the IOC container.

After the output view, the registered components and configuration components are found. All components. It also verifies whether the same component id is obtained by obtaining the same component id multiple times

In the output configuration component, you can find: com.boot.config.MyConfig$$EnhancerBySpringCGLIB$c4c3a02@7a26928a Is a CGLIB enhanced proxy object.

//         Call the method to get the component through the returned IOC container
//         In SpringBoot, the components in the IOC container are singleton by default, and the default number of calls in other places is the same
        User hanfu = run.getBean("user01", User.class);
        User user01 = run.getBean("user01", User.class);
        System.out.println(hanfu==user01);
​
        MyConfig myConfig = run.getBean("myConfig", MyConfig.class);
        System.out.println("myConfig = " + myConfig);

Since it is found that the configuration class is also a component, the object obtained by verifying the method called by the configuration component is also the same.

Full mode [full configuration]: check whether the IOC container starts slowly every time the component is called

A method proxyBeanMethods [proxy component method] is provided in the Configuration annotation. Its default value is true. If it is true, the objects obtained by calling the Configuration class component and then calling the Configuration method in the project are the same, that is, the proxy object calls the method. SpringBoot always checks whether there is this component in the container and takes it out to you, So it has always been one. Keep component single instance

Now the user wants to eat, so he introduces the food attribute and constructs get and set. In the configuration class, the method of registering food is called in the user method, and the user depends on food. When the proxyBeanMethods value is true, the component food obtained from the container is the same as the component object obtained by calling the getfood method using the user component. When the value is false, it is not the same

When proxyBeanMethods is true, it is the full mode. It can be used when there are dependencies between components. It can ensure that the obtained component object is the same.

@Bean
public User user01(){
    User user = new User("hanfu", "woman", "123456");
    user.setFood(beef());
    return user;
}

@Bean
public Food beef(){
    return new Food("beef","99");
}

Lite mode [lightweight configuration]: skip the viewing steps directly and start quickly

If it is modified to false, the objects obtained by configuring class components to call methods are not the same

If the value of proxyBeanMethods is false, it is a lite mode. If only components are registered, there is no dependency between components. Using this, spring boot can start faster

2. @ Import import Import components

@When the Import annotation is used, it is on the declared component, where the required parameter is a class array. Write the name of the component you want to Import into the container. Class in the array. It is to call the parameterless construction of classes in the array to build an object as a component. The classes in the array can be written by themselves or depend on them, and can be added if necessary

use

The results show that the output component is the full class name of the class when it is added.

@Import({User.class, SimpleObjectIdResolver.class})
​
@Configuration(proxyBeanMethods = true)
public class MyConfig {
    
    
  result
      --------------Split line-------------
s = xlw.com.boot.bean.User
s = user01
s = com.fasterxml.jackson.annotation.SimpleObjectIdResolver

3. @ Conditional conditional assembly

Operate the component according to the conditions required by the annotation.

According to the name of the annotation, it is not difficult to see the function represented by the annotation. Many of these annotations are used at the bottom of SpringBoot to assist in automatic assembly. These annotations are used to judge whether the current class or method exists or does not exist. Assembly of components.

This annotation can be used on classes and methods. If it is used on classes, the conditions will be met, and the components in the class will be automatically assembled into the IOC container. Otherwise, it will not have the same effect on methods as the class

 

Annotation parameters can be defined by type or component name. Add conditions to achieve the effect.

 

use

The annotation used here is to create the following two components only when there is a user component in the IOC container. Obviously, there is no such component.

@ConditionalOnBean(name = "user")
@Configuration(proxyBeanMethods = true)
public class MyConfig {
​
/*
    The Bean tag is used to identify the configuration class method. The return value is the component type, the method name is the component id, and the specific content returned is the object saved by the component in the container.
    If you want to set other component names, you can set the value attribute value in the Bean annotation
 */
    @Bean
    public User user01(){
        User user = new User("hanfu", "woman", "123456");
        user.setFood(beef());
        return user;
    }
​
    @Bean
    public Food beef(){
        return new Food("beef","99");
    }
    
    
    
    In the main program
        //         Judge whether a component with the current parameter name exists
        boolean user01 = run.containsBean("user01");
        boolean beef = run.containsBean("beef");
        System.out.println("Are there any components user01" +user01);
        System.out.println("Are there any components beef " + beef);
    
    
    result
        Are there any components user01false
        Are there any components beef false
        
        
        Change annotation to@ConditionalOnMissingBean(name = "user"),Namely IOC There are no components in the container user Just create these two components.
        
        
        result
        Are there any components user01true
        Are there any components beef true
        
        Here, it is not difficult to understand automatic assembly. If you introduce a scene, you will create components for you. If not, you will not load components

4. @ ImportResource import profile

In many project external dependencies, there are still components registered in the xml configuration file. Because there are many components, it is impossible to write them again when you use them yourself. This annotation @ ImportResource can be used to import the external file, so that the components in the configuration file can also be added to the current IOC container

use

@ImportResource("classpath:beans.xml")

In the configuration file

<?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="niuniu" class="xlw.com.boot.bean.User">
    </bean>
​
    <bean id="huahua" class="xlw.com.boot.bean.User"></bean>
</beans>

result

There are two components registered by the configuration file in the current IOC

      
​
  boolean niuniu = run.containsBean("niuniu");
        System.out.println("niuniu = " + niuniu);
        boolean huahua = run.containsBean("huahua");
        System.out.println("huahua = " + huahua);
        
        niuniu = true
        huahua = true

​

5. Configure binding

Using the annotation @ ConfigurationProperties, the properties of the bean can be bound with the SpringBoot core configuration file application.properties. Used to set property values.

a) , has been registered as a component

First register the class, and then bind the component to the fields specified in the core configuration file using the annotation @ ConfigurationProperties

Different attributes in the annotation represent different binding forms

@Component
@ConfigurationProperties(prefix = "children")
public class Children {
​
    private String name;
    private String age;
​
    public Children() {
    }
​
    public Children(String name, String age) {
        this.name = name;
        this.age = age;
    }
​
    public String getName() {
        return name;
    }
​
    public void setName(String name) {
        this.name = name;
    }
​
    public String getAge() {
        return age;
    }
​
    public void setAge(String age) {
        this.age = age;
    }
​
    @Override
    public String toString() {
        return "Children{" +
                "name='" + name + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}

In application.properties

children.name="haha"
children.age="12"

Now the component and configuration file have been bound, and the data is automatically injected into the controller to return the data to the page

@Autowired
private Children children;
​
@RequestMapping("/children")
public Children test02(){
    return children;
}

Finally get the data.

b) , not registered as a component

It is necessary to introduce external components and bind them to the core configuration file. Some classes are not registered as components. You can use annotations in configuration classes

@EnableConfigurationProperties(Children.class) add the class that needs to enable the binding function in the parameter

use

Now the bean is not registered as a component

@ConfigurationProperties(prefix = "children")
public class Children {
​
    private String name;
    private String age;
​
    public Children() {
    }
​
    public Children(String name, String age) {
        this.name = name;
        this.age = age;
    }
​
    public String getName() {
        return name;
    }
​
    public void setName(String name) {
        this.name = name;
    }
​
    public String getAge() {
        return age;
    }
​
    public void setAge(String age) {
        this.age = age;
    }
​
    @Override
    public String toString() {
        return "Children{" +
                "name='" + name + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}

In the configuration class

Add this statement to the class, register the parameter class as a component, and turn on the binding function at the same time

@EnableConfigurationProperties(Children.class)

You can also get the result after binding

Tags: Java Spring Boot Container

Posted on Mon, 06 Dec 2021 13:46:14 -0500 by graphic3