In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
How to understand the life cycle of Bean in Spring framework, aiming at this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.
Life cycle of 1.Bean
With regard to the life cycle of Bean, if we don't talk about the Spring, many people will actually think of New, instantiating the Bean in the form of a New object, and after we no longer use Bean, our Java will garbage collect the specified Bean.
But for Spring, the life cycle of Bean may be a headache, after all, Spring is so complex, and the management of Bean is very logical, each layer has each layer of steps.
If we go to Baidu now to search for all the Bean lifecycles of Spring, many people will explain this.
After the IoC container starts, the corresponding bean is not instantiated immediately. In this case, the container only has the BeanDefinition of all objects (BeanDefinition: the container parses and analyzes the XML configuration information loaded by certain tools, and groups the analyzed information into the corresponding BeanDefinition). It is only possible to trigger the activity of the Bean instantiation phase when getBean () is called.
There are some things that are not explained thoroughly, such as why it is possible to trigger the instantiation of Bean only when getBean () is called.
two。 Life cycle flow chart
2.1 simplified layout solution
In this diagram, the life cycle of Bean in Spring is divided into several steps, which are:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Instantiate the Bean object through the constructor.
Set the properties of the object through the setter method.
Through Aware, which is his subclass BeanNameAware, call the setBeanName () method of Bean to pass the ID of Bean (the ID registered in XML). The setBeanName method is called when bean is initialized. Through this method, you can get the ID registered by BeanFactory and Bean in XML.
If Bean implements BeanFactoryAware, then the parameters passed in by the factory call setBeanFactory (BeanFactory var1) are themselves.
Pass the Bean instance to the postProcessBeforeInitialization front method in BeanPostProcessor.
Complete the initialization of Bean
Pass the Bean instance to the postProcessAfterInitialization post method in BeanPostProcessor.
At this point, Bean is able to call the destroy method in DisposableBean for destruction at the last time.
And A Fan thinks that if the interviewer asks this question during the interview, you start with the diagram and then tell him all this, then corresponding to these answers, if you do not continue to dig deep into the content, it may be enough.
And then we have to fundamentally demonstrate what Ah Fan wrote.
It is sometimes difficult for us to remember the details, or we may not understand them deeply, and we can remember them from four to five aspects.
Construction instantiation
Attribute assignment
Complete initialization
(pre-and post-processing)
Destroy after use
By memorizing from these five aspects, we may be able to expand the picture and answer the interviewer's questions succinctly.
Code verification
Package com.yld.bean; import org.springframework.beans.factory.BeanNameAware; public class Person implements BeanNameAware {private String name; / * implement the override method on the class * @ param s * / @ Override public void setBeanName (String s) {System.out.println ("call setName assignment in BeanNameAware") } public Person () {} / * * attribute assignment * @ param name * / public void setName (String name) {System.out.println ("set object property setName ()."); this.name = name } / * Bean initialization * / public void initBeanPerson () {System.out.println ("initialize Bean");} / * Bean method use: speak * / public void speak () {System.out.println ("use Bean's Speak method") } / * destroy Bean * / public void destroyBeanPerson () {System.out.println ("destroy Bean");}}
Main method
Public static void main (String [] args) {ClassPathXmlApplicationContext pathXmlApplicationContext = new ClassPathXmlApplicationContext ("applicationContext.xml"); Person person = (Person) pathXmlApplicationContext.getBean ("person"); person.speak (); pathXmlApplicationContext.close ();}
Display of running results
D:\ develop\ JDK8\ jdk1.8.0_181\ bin\ java.exe "- javaagent:D:\ develop\ IDEA\ IntelliJ IDEA 2018.1.8\ lib\ idea_rt.jar=63906:D:\ develop\ IDEA\ IntelliJ IDEA 2018.1.8\ bin"-Dfile.encoding=UTF-8-classpath D:\ develop\ JDK8\ jdk1.8.0_181\ jre\ lib\ charsets.jar;D:\ develop\ JDK8\ jdk1.8.0_181\ jre\ lib\ deploy.jar D:\ develop\ JDK8\ jdk1.8.0_181\ jre\ lib\ ext\ access-bridge-64.jar;D:\ develop\ JDK8\ jdk1.8.0_181\ jre\ lib\ ext\ cldrdata.jar;D:\ develop\ JDK8\ jdk1.8.0_181\ jre\ lib\ ext\ dnsns.jar;D:\ develop\ JDK8\ jdk1.8.0_181\ jre\ lib\ ext\ jaccess.jar;D:\ develop\ JDK8\ jdk1.8.0_181\ jre\ lib\ ext\ jfxrt.jar D:\ develop\ JDK8\ jdk1.8.0_181\ jre\ lib\ ext\ localedata.jar;D:\ develop\ JDK8\ jdk1.8.0_181\ jre\ lib\ ext\ nashorn.jar;D:\ develop\ JDK8\ jdk1.8.0_181\ jre\ lib\ ext\ sunec.jar;D:\ develop\ JDK8\ jdk1.8.0_181\ jre\ lib\ ext\ sunjce_provider.jar;D:\ develop\ JDK8\ jdk1.8.0_181\ jre\ lib\ ext\ sunmscapi.jar D:\ develop\ JDK8\ jdk1.8.0_181\ jre\ lib\ ext\ sunpkcs11.jar;D:\ develop\ JDK8\ jdk1.8.0_181\ jre\ lib\ ext\ zipfs.jar;D:\ develop\ JDK8\ jdk1.8.0_181\ jre\ lib\ javaws.jar;D:\ develop\ JDK8\ jdk1.8.0_181\ jre\ lib\ jce.jar;D:\ develop\ JDK8\ jdk1.8.0_181\ jre\ lib\ jfr.jar D:\ develop\ JDK8\ jdk1.8.0_181\ jre\ lib\ jfxswt.jar;D:\ develop\ JDK8\ jdk1.8.0_181\ jre\ lib\ jsse.jar;D:\ develop\ JDK8\ jdk1.8.0_181\ jre\ lib\ management-agent.jar;D:\ develop\ JDK8\ jdk1.8.0_181\ jre\ lib\ plugin.jar;D:\ develop\ JDK8\ jdk1.8.0_181\ jre\ lib\ resources.jar D:\ develop\ JDK8\ jdk1.8.0_181\ jre\ lib\ rt.jar;D:\ develop\ IDEAProject\ KaiYuan\ target\ classes;C:\ Users\ Administrator\ .m2\ repository\ org\ springframework\ boot\ spring-boot-starter\ 2.1.8.RELEASE\ spring-boot-starter-2.1.8.RELEASE.jar;C:\ Users\ Administrator\ .m2\ repository\ org\ springframework\ boot\ spring-boot\ 2.1.8.RELEASE\ spring-boot-2.1.8.RELEASE.jar C:\ Users\ Administrator\ .m2\ repository\ org\ springframework\ spring-context\ 5.1.9.RELEASE\ spring-context-5.1.9.RELEASE.jar;C:\ Users\ Administrator\ .m2\ repository\ org\ springframework\ spring-aop\ 5.1.9.RELEASE\ spring-aop-5.1.9.RELEASE.jar;C:\ Users\ Administrator\ .m2\ repository\ org\ springframework\ spring-beans\ 5.1.9.RELEASE\ spring-beans-5.1.9.RELEASE.jar C:\ Users\ Administrator\ .m2\ repository\ org\ springframework\ spring-expression\ 5.1.9.RELEASE\ spring-expression-5.1.9.RELEASE.jar;C:\ Users\ Administrator\ .m2\ repository\ org\ springframework\ boot\ spring-boot-autoconfigure\ 2.1.8.RELEASE\ spring-boot-autoconfigure-2.1.8.RELEASE.jar C:\ Users\ Administrator\ .m2\ repository\ org\ boot\ spring-boot-starter-logging\ 2.1.8.RELEASE\ spring-boot-starter-logging-2.1.8.RELEASE.jar;C:\ Users\ Administrator\ .m2\ repository\ ch\ qos\ logback\ logback-classic\ 1.2.3\ logback-classic-1.2.3.jar;C:\ Users\ Administrator\ .m2\ repository\ ch\ qos\ logback\ logback-core\ 1.2.3\ logback-core-1.2.3.jar C:\ Users\ Administrator\ .m2\ repository\ org\ logging\ log4j\ log4j-to-slf4j\ 2.11.2\ log4j-to-slf4j-2.11.2.jar;C:\ Users\ Administrator\ .m2\ repository\ org\ apache\ logging\ log4j\ log4j-api\ 2.11.2\ log4j-api-2.11.2.jar;C:\ Users\ Administrator\ .m2\ repository\ org\ slf4j\ jul-to-slf4j\ 1.7.28\ jul-to-slf4j-1.7.28.jar C:\ Users\ Administrator\ .m2\ repository\ javax\ annotation\ javax.annotation-api\ 1.3.2\ javax.annotation-api-1.3.2.jar;C:\ Users\ Administrator\ .m2\ repository\ org\ springframework\ spring-core\ 5.1.9.RELEASE\ spring-core-5.1.9.RELEASE.jar;C:\ Users\ Administrator\ .m2\ repository\ org\ springframework\ spring-jcl\ 5.1.9.RELEASE\ spring-jcl-5.1.9.RELEASE.jar C:\ Users\ Administrator\ .m2\ repository\ org\ yaml\ snakeyaml\ 1.23\ snakeyaml-1.23.jar C:\ Users\ Administrator\ .m2\ repository\ org\ slf4j\ slf4j-api\ 1.7.28\ slf4j-api-1.7.28.jar com.yld.bean.Test 16VOV 54VOV 58.817 [main] DEBUG org.springframework.context.support.ClassPathXmlApplicationContext-Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@123772c4 16VOV 59.074 [main] DEBUG org.springframework.beans.factory.xml.XmlBeanDefinitionReader-Loaded 1 bean definitions from class path resource [applicationContext.xml] 1654VOV 59.121 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory-Creating shared instance of singleton bean 'person' sets the object property setName ().. Initialize Bean by calling the setName assignment in BeanNameAware using the Speak method of Bean 16 Bean 54 Bean 59.232 [main] DEBUG org.springframework.context.support.ClassPathXmlApplicationContext-Closing org.springframework.context.support.ClassPathXmlApplicationContext@123772c4, started on Sun Jun 07 16:54:58 CST 2020 destroys Bean Process finished with exit code 0
Is it the same as everyone expected? After answering the interviewer with a case, we'd better study the part of the source code. After all, if we study it clearly, we will understand it more deeply, right?
InstantiationAwareBeanPostProcessor
This class is an inherited BeanPostProcessor, but what is the purpose of this class? The source comments explain something like this:
Method 1:
@ Nullable default Object postProcessBeforeInstantiation (Class beanClass, String beanName) throws BeansException {return null;} applies this Bean processor before the target Bean is instantiated. The returned bean object may be the use of a proxy bean rather than the target
That is to say, postProcessBeforeInstantiation is called before bean instantiation, is this also another face pilot AOP we use in the interview? When the interviewer asks you to give an example, you directly use the source code in this Spring to explain to him, and let the interviewer scratch your eyes every minute to see if there is any.
Method 2: you can see that the method is within the attribute assignment method, but before the assignment operation is actually performed. The return value is boolean.
Default boolean postProcessAfterInstantiation (Object bean, String beanName) throws BeansException {return true;}
Can you still understand that if the return value is false, then there will be an assignment failure, that is, indirectly blocking the assignment.
And the initialized class has the same BeanPostProcessor
Method 1:
Any callback initialized before Bean, such as @ Nullable default Object postProcessBeforeInitialization (Object bean, String beanName) throws BeansException {return bean;} after initializing the property setting of Bean
Method 2:
Apply this Bean post processor to give a new Bean instance, any callback after Bean initialization (such as initializing the property setting of Bean {@ code} or a custom init method). The bean has been populated with property values. The returned bean instance may be the original wrapper.
Apply this Bean post processor to give a new Bean instance, any callback after Bean initialization (such as initializing the property setting of Bean {@ code} or a custom init method). The bean has been populated with property values. The returned bean instance may be the original wrapper. @ Nullable default Object postProcessAfterInitialization (Object bean, String beanName) throws BeansException {return bean;}
Similarly, the meaning of the translation of the comments is also very clear, which is why A Fan likes to download a plug-in to read the comments. After all, if you look at what other people understand and what you understand, sometimes there is a big gap.
This is the answer to the question on how to understand the life cycle of Bean in the Spring framework. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.