Spring Bean的生命周期是面试过程中经常会问到的一道题目,为了不单纯的北宋八股文,还是决定自己去代码验证下答案的正确与否,同时加深自己对Spring Bean的认识。 首先,贴一下网上的答案: Spring 中Bean 的生命周期
如上图所示,Bean 的生命周期还是比较复杂的,下面来对上图每一个步骤做文字描述: 1、Spring启动,查找并加载需要被Spring管理的bean,进行Bean的实例化 2、Bean实例化后对将Bean的引入和值注入到Bean的属性中 3、如果Bean实现了BeanNameAware接口的话,Spring将Bean的Id传递给setBeanName()方法 4、如果Bean实现了BeanFactoryAware接口的话,Spring将调用setBeanFactory()方法,将BeanFactory容器实例传入 5、如果Bean实现了ApplicationContextAware接口的话,Spring将调用Bean的setApplicationContext()方法,将bean所在应用上下文引用传入进来。 6、如果Bean实现了BeanPostProcessor接口,Spring就将调用他们的postProcessBeforeInitialization()方法。 7、如果Bean 实现了InitializingBean接口,Spring将调用他们的afterPropertiesSet()方法。类似的,如果bean使用init-method声明了初始化方法,该方法也会被调用 8、如果Bean 实现了BeanPostProcessor接口,Spring就将调用他们的postProcessAfterInitialization()方法。 9、此时,Bean已经准备就绪,可以被应用程序使用了。他们将一直驻留在应用上下文中,直到应用上下文被销毁。 10、如果bean实现了DisposableBean接口,Spring将调用它的destory()接口方法,同样,如果bean使用了destory-method 声明销毁方法,该方法也会被调用。
package com.example.springbean.component;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class MySpringBean implements BeanNameAware, BeanFactoryAware, ApplicationContextAware, InitializingBean, DisposableBean {
public MySpringBean() {
System.out.println("Bean通过构造方法进行实例化");
}
@Override
public void setBeanName(String name) {
System.out.println("Bean实现了BeanNameAware接口,执行setBeanName()方法,name = " + name);
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
System.out.println("Bean实现了BeanFactoryAware接口,执行setBeanFactory(),beanFactory=" + beanFactory.getClass().getCanonicalName());
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("Bean实现了ApplicationContextAware接口,调用setApplicationContext()方法,applicationContext=" + applicationContext.getDisplayName());
}
@Override
public void destroy() throws Exception {
System.out.println("Bean实现了DisposableBean接口,调用destroy()方法");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Bean 实现了InitializingBean接口,调用afterPropertiesSet()方法");
}
}
package com.example.springbean.component;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
@Component
public class MySpringBeanProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof MySpringBean) {
System.out.println("Bean实现了BeanPostProcessor接口,调用postProcessBeforeInitialization()");
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof MySpringBean) {
System.out.println("Bean实现了BeanPostProcessor接口,postProcessAfterInitialization()");
}
return bean;
}
}
D:\software\Java\jdk1.8.0_221\bin\java.exe -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always "-javaagent:D:\software\IntelliJ IDEA 2021.2.3\lib\idea_rt.jar=4880:D:\software\IntelliJ IDEA 2021.2.3\bin" -Dcom.sun.management.jmxremote -Dspring.jmx.enabled=true -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true -Dfile.encoding=UTF-8 -classpath D:\software\Java\jdk1.8.0_221\jre\lib\charsets.jar;D:\software\Java\jdk1.8.0_221\jre\lib\deploy.jar;D:\software\Java\jdk1.8.0_221\jre\lib\ext\access-bridge-64.jar;D:\software\Java\jdk1.8.0_221\jre\lib\ext\cldrdata.jar;D:\software\Java\jdk1.8.0_221\jre\lib\ext\dnsns.jar;D:\software\Java\jdk1.8.0_221\jre\lib\ext\jaccess.jar;D:\software\Java\jdk1.8.0_221\jre\lib\ext\jfxrt.jar;D:\software\Java\jdk1.8.0_221\jre\lib\ext\localedata.jar;D:\software\Java\jdk1.8.0_221\jre\lib\ext\nashorn.jar;D:\software\Java\jdk1.8.0_221\jre\lib\ext\sunec.jar;D:\software\Java\jdk1.8.0_221\jre\lib\ext\sunjce_provider.jar;D:\software\Java\jdk1.8.0_221\jre\lib\ext\sunmscapi.jar;D:\software\Java\jdk1.8.0_221\jre\lib\ext\sunpkcs11.jar;D:\software\Java\jdk1.8.0_221\jre\lib\ext\zipfs.jar;D:\software\Java\jdk1.8.0_221\jre\lib\javaws.jar;D:\software\Java\jdk1.8.0_221\jre\lib\jce.jar;D:\software\Java\jdk1.8.0_221\jre\lib\jfr.jar;D:\software\Java\jdk1.8.0_221\jre\lib\jfxswt.jar;D:\software\Java\jdk1.8.0_221\jre\lib\jsse.jar;D:\software\Java\jdk1.8.0_221\jre\lib\management-agent.jar;D:\software\Java\jdk1.8.0_221\jre\lib\plugin.jar;D:\software\Java\jdk1.8.0_221\jre\lib\resources.jar;D:\software\Java\jdk1.8.0_221\jre\lib\rt.jar;D:\Workspace\demo\spring-bean\target\classes;D:\software\Repository\MavenLocalRepository\org\springframework\boot\spring-boot-starter\2.6.7\spring-boot-starter-2.6.7.jar;D:\software\Repository\MavenLocalRepository\org\springframework\boot\spring-boot\2.6.7\spring-boot-2.6.7.jar;D:\software\Repository\MavenLocalRepository\org\springframework\spring-context\5.3.19\spring-context-5.3.19.jar;D:\software\Repository\MavenLocalRepository\org\springframework\boot\spring-boot-autoconfigure\2.6.7\spring-boot-autoconfigure-2.6.7.jar;D:\software\Repository\MavenLocalRepository\org\springframework\boot\spring-boot-starter-logging\2.6.7\spring-boot-starter-logging-2.6.7.jar;D:\software\Repository\MavenLocalRepository\ch\qos\logback\logback-classic\1.2.11\logback-classic-1.2.11.jar;D:\software\Repository\MavenLocalRepository\ch\qos\logback\logback-core\1.2.11\logback-core-1.2.11.jar;D:\software\Repository\MavenLocalRepository\org\apache\logging\log4j\log4j-to-slf4j\2.17.2\log4j-to-slf4j-2.17.2.jar;D:\software\Repository\MavenLocalRepository\org\apache\logging\log4j\log4j-api\2.17.2\log4j-api-2.17.2.jar;D:\software\Repository\MavenLocalRepository\org\slf4j\jul-to-slf4j\1.7.36\jul-to-slf4j-1.7.36.jar;D:\software\Repository\MavenLocalRepository\jakarta\annotation\jakarta.annotation-api\1.3.5\jakarta.annotation-api-1.3.5.jar;D:\software\Repository\MavenLocalRepository\org\springframework\spring-core\5.3.19\spring-core-5.3.19.jar;D:\software\Repository\MavenLocalRepository\org\springframework\spring-jcl\5.3.19\spring-jcl-5.3.19.jar;D:\software\Repository\MavenLocalRepository\org\yaml\snakeyaml\1.29\snakeyaml-1.29.jar;D:\software\Repository\MavenLocalRepository\org\slf4j\slf4j-api\1.7.36\slf4j-api-1.7.36.jar;D:\software\Repository\MavenLocalRepository\org\springframework\boot\spring-boot-starter-web\2.6.7\spring-boot-starter-web-2.6.7.jar;D:\software\Repository\MavenLocalRepository\org\springframework\boot\spring-boot-starter-json\2.6.7\spring-boot-starter-json-2.6.7.jar;D:\software\Repository\MavenLocalRepository\com\fasterxml\jackson\core\jackson-databind\2.13.2.1\jackson-databind-2.13.2.1.jar;D:\software\Repository\MavenLocalRepository\com\fasterxml\jackson\core\jackson-annotations\2.13.2\jackson-annotations-2.13.2.jar;D:\software\Repository\MavenLocalRepository\com\fasterxml\jackson\core\jackson-core\2.13.2\jackson-core-2.13.2.jar;D:\software\Repository\MavenLocalRepository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.13.2\jackson-datatype-jdk8-2.13.2.jar;D:\software\Repository\MavenLocalRepository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.13.2\jackson-datatype-jsr310-2.13.2.jar;D:\software\Repository\MavenLocalRepository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.13.2\jackson-module-parameter-names-2.13.2.jar;D:\software\Repository\MavenLocalRepository\org\springframework\boot\spring-boot-starter-tomcat\2.6.7\spring-boot-starter-tomcat-2.6.7.jar;D:\software\Repository\MavenLocalRepository\org\apache\tomcat\embed\tomcat-embed-core\9.0.62\tomcat-embed-core-9.0.62.jar;D:\software\Repository\MavenLocalRepository\org\apache\tomcat\embed\tomcat-embed-el\9.0.62\tomcat-embed-el-9.0.62.jar;D:\software\Repository\MavenLocalRepository\org\apache\tomcat\embed\tomcat-embed-websocket\9.0.62\tomcat-embed-websocket-9.0.62.jar;D:\software\Repository\MavenLocalRepository\org\springframework\spring-web\5.3.19\spring-web-5.3.19.jar;D:\software\Repository\MavenLocalRepository\org\springframework\spring-beans\5.3.19\spring-beans-5.3.19.jar;D:\software\Repository\MavenLocalRepository\org\springframework\spring-webmvc\5.3.19\spring-webmvc-5.3.19.jar;D:\software\Repository\MavenLocalRepository\org\springframework\spring-aop\5.3.19\spring-aop-5.3.19.jar;D:\software\Repository\MavenLocalRepository\org\springframework\spring-expression\5.3.19\spring-expression-5.3.19.jar com.example.springbean.SpringBeanApplication
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.6.7)
2022-05-08 22:14:07.206 INFO 22504 --- [ main] c.e.springbean.SpringBeanApplication : Starting SpringBeanApplication using Java 1.8.0_221 on LAPTOP-CANO6289 with PID 22504 (D:\Workspace\demo\spring-bean\target\classes started by Lenovo in D:\Workspace\demo\spring-bean)
2022-05-08 22:14:07.208 INFO 22504 --- [ main] c.e.springbean.SpringBeanApplication : No active profile set, falling back to 1 default profile: "default"
2022-05-08 22:14:07.698 INFO 22504 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-05-08 22:14:07.703 INFO 22504 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-05-08 22:14:07.703 INFO 22504 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.62]
2022-05-08 22:14:07.793 INFO 22504 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-05-08 22:14:07.793 INFO 22504 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 560 ms
Bean通过构造方法进行实例化
Bean实现了BeanNameAware接口,执行setBeanName()方法,name = mySpringBean
Bean实现了BeanFactoryAware接口,执行setBeanFactory(),beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory
Bean实现了ApplicationContextAware接口,调用setApplicationContext()方法,applicationContext=org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@4e08711f
Bean实现了BeanPostProcessor接口,调用postProcessBeforeInitialization()
Bean 实现了InitializingBean接口,调用afterPropertiesSet()方法
Bean实现了BeanPostProcessor接口,postProcessAfterInitialization()
2022-05-08 22:14:07.967 INFO 22504 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-05-08 22:14:07.973 INFO 22504 --- [ main] c.e.springbean.SpringBeanApplication : Started SpringBeanApplication in 0.981 seconds (JVM running for 1.672)
Bean实现了DisposableBean接口,调用destroy()方法
Process finished with exit code 130
|