Suddenly I feel that the question and answer style is very suitable for explaining some questions. In this article, we will use the question and answer story style to answer the above question. This is what I was asked in the previous interview. This time, let's discuss this issue thoroughly.
Introduction of Bean Life Cycle Concept
One day, Xiao Chen felt a little tired of being in this company and was going to run away quietly, so he went to work while preparing the interview questions while going to work. One day, he saw the life cycle of such an interview question, Spring Bean, and he couldn't understand it. He thought of his leader, the leader with a very wide technology stack, so he found the leader and asked: leader, I don't quite understand the concept of a Spring Bean life cycle, can you tell me if you have time?
The leader said: Wait a minute, I am dealing with a problem, I will go to you in a while. Fifteen minutes later, the leader came to Xiao Chen's workstation and said: Now let's come to the concept of Spring Bean's life cycle! Are you ready? Xiao Chen nodded.
The leader said: First of all, we need to figure out the meaning of life cycle. The English of life cycle is Life Cycle. In short, it is some extended interfaces provided by Spring. If the bean implements these interfaces, the application will call back during the startup process. methods of these interfaces. In Spring, the life of a bean is usually to create its object first, and then fill its properties. If the bean implements the extension interface provided by Spring, these methods will be called back in turn when the IOC container is loaded. The callback sequence of the corresponding methods of these extended interfaces is as follows:
After drawing the picture, the leader asked, "Which word in this is familiar to you? Tell me about it."
Xiao Chen wondered how the PPT he was leading was so proficient in drawing, so he continued to answer: I seem to have only seen ApplicationContext. When I first learned the Spring framework, I used this ApplicatonContext to get the objects loaded into the IOC container, like the following:
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringBeanConfig.class);
applicationContext.getBean(StudentService.class);
}
The leader nodded and then said: Most of the entry starts with such an example, said here, looking at the above code, which design pattern do you think of?
Xiao Chen replied: This reminds me of the simple factory pattern, I give an identity, and the ApplicationContext loads the corresponding object for me.
The leader nodded: ApplicationContext inherits from BeanFactory, and the simple factory pattern is indeed used above. The above interfaces with Aware inherit from the Aware interface. Subclasses will provide richer functionality to the parent class. setBeanName will swap in the Bean Id and Bean name that implement the BeanNameAware interface, that is to say, after the container initializes the bean and fills in the properties of the bean, it will call back BeanNameAware, ApplicationContextAware, postProcessBeforeInitialization of BeanPostProcessor, afterPropertiesSet method of InitializingBean, and init of Bean -method method, method of postProcessAfterInitialization of BeanPostProcessor. It should be noted here that BeanNameAware and ApplicationContextAware will only be called back in sequence. After each bean is initialized, it will call back the two methods of BeanPostProcessor. It actually ends here. Let's write a code to demonstrate the above sequence:
public class BeanLifeCycleDemo implements BeanNameAware, BeanFactoryAware, ApplicationContextAware, InitializingBean,BeanPostProcessor{
private MuttonSoupService muttonSoupService;
public BeanLifeCycleDemo( ) {
System.out.println("1.构造函数初始化bean");
}
@Autowired
public void setMuttonSoupService(MuttonSoupService muttonSoupService) {
System.out.println("2.先填充属性-");
this.muttonSoupService = muttonSoupService;
}
public void sayHelloWorld(){
System.out.println("hello world");
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
System.out.println("----4-- 接着是BeanFactoryAware");
}
@Override
public void setBeanName(String name) {
System.out.println("3---- name+" + name);
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("----7 afterPropertiesSet");
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("------5 applicationContextAware");
}
public void initMethod(){
System.out.println("6 init-method");
}
/**
* @param bean
* @param beanName
* @return
* @throws BeansException
*/
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("---- postProcessBeforeInitialization"+beanName);
return bean;
}
/**
* @param bean
* @param beanName
* @return
* @throws BeansException
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("---- postProcessAfterInitialization");
return bean;
}
}
@Configuration
public class SpringBeanConfig {
@Bean(initMethod = "initMethod")
public BeanLifeCycleDemo beanLifeCycleDemo(){
return new BeanLifeCycleDemo();
}
}
@SpringBootTest
class SsmApplicationTests {
@Autowired
private BeanLifeCycleDemo beanLifeStyleDemo;
// 直接运行测试即可
@Test
public void test(){
}
}
Output result:
Xiao Chen was a little happy when he saw the result, the leader overturned, so he said: The order of your leader is not the same as the order in the picture above. I have one more question, is this bean immortal?
The leader said lightly: I'm showing it to you on purpose, pay attention to this BeanPostProcessor, the Bean corresponding to this interface needs to be pre-loaded to achieve the above effect. The loading sequence of Spring Bean is shown in the following figure (the following picture is found on the Internet):
So we can implement the above sequence by writing a BeanPostProcessor bean. As for the end of Bean's life, I actually tested you on purpose. In fact, it is just an interface and an attribute. The interface is DisposableBean, and the attribute has a destroyMethod in @Bean. These two properties also have alternate annotations, init-method=@PostConstruct, @PreDestroy=destroyMethod. Combining the above figure, we can roughly understand the process of loading beans in the Spring IOC container. The so-called life cycle can be regarded as a callback in the process of loading beans to some extent.
Xiao Chen said: Thank you for your leadership, I feel that I understand this concept more thoroughly. Compared with the life cycle, I prefer your statement of callback.
References
- Spring – Bean Life Cycle https://howtodoinjava.com/spring-core/spring-bean-life-cycle/
- What design patterns does Spring use https://199604.com/2188
- BeanPostProcessor - a bridge connecting Spring IOC and AOP https://zhuanlan.zhihu.com/p/38208324
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。