Spring core interface InitializingBean

1. The InitializingBean interface provides an initialization method for the bean. It only includes the afterPropertiesSet method. All classes that inherit this interface will execute this method when initializing the bean.
2. When spring initializes the bean, if the bean implements the InitializingBean interface, the afterPropertiesSet method will be called automatically.
3. When Spring initializes a bean, if the bean implements the InitializingBean interface and specifies the init-method in the configuration file, the system calls the afterPropertieSet() method first, and then calls the method specified in the init-method.

1. Spring provides two ways to initialize beans for beans, implement the InitializingBean interface, implement the afterPropertiesSet method, or specify in the configuration file through the init-method, and the two methods can be used at the same time.
2. Implementing the InitializingBean interface is to directly call the afterPropertiesSet method, which is more efficient than calling the method specified by init-method through reflection, but the init-method method eliminates the dependence on spring.
3. If an error occurs when calling the afterPropertiesSet method, the method specified by init-method will not be called.

There are two types of beans in Spring, one is ordinary beans, and the other is factory beans, FactoryBean. The factory bean is different from the ordinary bean, the object it returns is not an instance of the specified class, what it returns is the object returned by the getObject method of the factory bean.

Usage scenarios: 1. Whether the class is a singleton is controlled externally, and the class itself cannot perceive it. 2. The initialization operation before the creation of the class is completed in afterPropertiesSet().

There are two ways to initialize beans in spring:
first: implement the InitializingBean interface, and then implement the method of afterPropertiesSet
second: reflection principle, the configuration file uses the init-method tag to directly inject the bean

The same point: implement the initialization of the injected bean.

Differences:
(1) The implementation methods are inconsistent.
(2) The interface is more efficient than the configuration, but the configuration eliminates the dependence on spring. The implementation of the InitializingBean interface still relies on spring.
Code example:

@Component
public class TestInitializingBean implements InitializingBean {
    
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public void afterPropertiesSet() throws Exception {
    
    
        System.out.println("ceshi InitializingBean");
    }
    public void testInit(){
    
    
        System.out.println("ceshi init-method");
    }
}

Guess you like

Origin blog.csdn.net/GBS20200720/article/details/127765569