SpringBean 初始化的执行各方法的顺序
共计 2085 个字符,预计需要花费 6 分钟才能阅读完成。
Spring 容器在创建 SpringBean 的时候,会帮我们自动给属性赋值,还有一些初始化方法和一些增强的方法。
因此,了解这些方法的顺序很有必要,这样可以了解方法增强的时机,有助于更好地编写代码。
通过如下案例可以看见执行的先后顺序:
MyBean.java
@Data
public class MyBean implements InitializingBean {
private String value;
public MyBean() {
System.out.println("构造方法...");
}
@Autowired
public void setValue(@Value("${JAVA_HOME}") String value){
this.value = value;
System.out.println("属性赋值...");
}
public void initMethod(){
System.out.println("initMethod...");
}
public void destroyMethod(){
System.out.println("destroyMethod...");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet...");
}
@PostConstruct
public void postConstruct() {
System.out.println("PostConstruct...");
}
@PreDestroy
public void preDestroy() {
System.out.println("PreDestroy...");
}
}
后处理器 MyBeanPostProcessor.java
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("BeanPostProcessor的before...");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("BeanPostProcessor的after...");
return bean;
}
}
配置类 Config.java
@Configuration
public class Config {
// 这里如果配置 @ComponentScan 就无法得到 initMethod 的执行顺序
@Bean(initMethod = "initMethod", destroyMethod = "destroyMethod")
public MyBean myBean(){
return new MyBean();
}
@Bean
public MyBeanPostProcessor myBeanPostProcessor(){
return new MyBeanPostProcessor();
}
}
测试类 BeanInitTest.java
public class BeanInitTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class);
System.out.println("#=======================================#");
applicationContext.close();
}
}
执行结果如下:
构造方法...
属性赋值...
BeanPostProcessor的before...
PostConstruct...
afterPropertiesSet...
initMethod...
BeanPostProcessor的after...
#=======================================#
PreDestroy...
destroyMethod...
由此可以得到结论,创建时最开始执行构造函数,再执行属性赋值方法,然后执行 bean 后处理器的 before 方法。再是执行 @PostConstruct 标注的方法,然后执行 InitializingBean 接口的 afterPropertiesSet 方法,再执行 @Bean 指定的初始化方法,再执行 bean 后处理器的 after 方法。
而执行销毁时,先执行 @PreDestroy 标注的方法,再执行 @Bean 指定的销毁方法。
Tips:清朝云网络工作室
1、本网站名称 清朝云资源网
2、本站永久连接https://www.qcyqq.com/8141.html
3、本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长进行删除处理。
4、本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
5、本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
6、本站资源大多存储在云盘,如发现链接失效,请联系我们我们会第一时间更新。
7.站长联系方式:766378891@qq.com
2、本站永久连接https://www.qcyqq.com/8141.html
3、本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长进行删除处理。
4、本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
5、本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
6、本站资源大多存储在云盘,如发现链接失效,请联系我们我们会第一时间更新。
7.站长联系方式:766378891@qq.com
THE END
0
二维码
海报
SpringBean 初始化的执行各方法的顺序
共计 2085 个字符,预计需要花费 6 分钟才能阅读完成。 ……




共有 0 条评论