世上最全的@PostConstruct注解说明
下文笔者讲述"@PostConstruct注解"的说明,如下所示
@PostConstruct注解使用示例
@PostConstruct注意事项
1.@PostConstruct注解是java原生注解
不是Spring提供的注解
2.@PostConstruct注解用于修饰非静态的void()方法
3.@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,且只会被服务器运行一次
4.@PostConstruct修饰的方法在构造函数之后执行,init()方法之前运行
Spring中被@PostConstruct注解修饰的方法,运行顺序
Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注解的方法)例:
@PostConstruct注解使用示例
package com.java265.util;
import com.java265.service.MyMethorClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class MyUtils {
private static Utils staticInstance = new Utils();
@Autowired
private MyMethorClassService myService;
@PostConstruct
public void init(){
staticInstance.myService = myService;
}
public static Integer invokeBean(){
return staticInstance.myService.add(888,999);
}
}
@PostConstruct注解如何被Spring运行呢?
Spring初始化回调方法的查找
AbstractApplicationContext.finishBeanFactoryInitialization(...);
beanFactory.preInstantiateSingletons();
DefaultlistableBeanFactory.getBean(beanName);
AbstractBeanFactory.doGetBean();
AbstractAutowireCapableBeanFactory.createBean(....)
populateBean(beanName, mbd, instanceWrapper);
initializeBean(...)
//调用BeanPostProcessor.postProcessBeforeInitialization()方法
applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
//调用BeanPostProcessor.postProcessBeforeInitialization()方法
applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
BeanPostProcessor有个实现类CommonAnnotationBeanPostProcessor
用于处理@PostConstruct @PreDestroy注解
CommonAnnotationBeanPostProcessor的父类InitDestroyAnnotationBeanPostProcessor()
InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization()
InitDestroyAnnotationBeanPostProcessor.findLifecycleMetadata()
// 组装生命周期元数据
InitDestroyAnnotationBeanPostProcessor.buildLifecycleMetadata()
// 查找@PostConstruct注释的方法
InitDestroyAnnotationBeanPostProcessor.initAnnotationType
// 查找@PreDestroy注释方法
InitDestroyAnnotationBeanPostProcessor.destroyAnnotationType
// 反射调用
metadata.invokeInitMethods(bean, beanName);
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


