执行顺序:
静态代码块 > 构造方法 > BeanFactoryAware > ApplicationContextAware > @PostConstruct > InitializingBean > InstantiationAwareBeanPostProcessor > BeanPostProcessor > ApplicationRunner
java
/**
* 执行顺序:
* 静态代码块 > 构造方法 > BeanFactoryAware > ApplicationContextAware > @PostConstruct > InitializingBean > InstantiationAwareBeanPostProcessor > BeanPostProcessor > ApplicationRunner
* */
@Component
public class BeanPostProcessorTest implements BeanPostProcessor, InitializingBean, BeanFactoryAware, ApplicationContextAware, InstantiationAwareBeanPostProcessor, ApplicationRunner {
static Integer count = 1;
public BeanPostProcessorTest(){
System.out.println(count++ + "构造函数初始化...");
}
static {
System.out.println(count++ + "静态代码块...");
}
@PostConstruct
public void init(){
System.out.println(count++ + "PostConstruct...");
}
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
System.out.println(count++ + "InstantiationAwareBeanPostProcessor-> postProcessBeforeInstantiation...");
return InstantiationAwareBeanPostProcessor.super.postProcessBeforeInstantiation(beanClass, beanName);
}
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
System.out.println(count++ + "InstantiationAwareBeanPostProcessor-> postProcessAfterInstantiation...");
return InstantiationAwareBeanPostProcessor.super.postProcessAfterInstantiation(bean, beanName);
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
// 在 Bean 初始化之前添加逻辑
System.out.println(count++ + "BeanPostProcessor-> postProcessBeforeInitialization...");
return bean; // 返回原始或修改后的 Bean
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
System.out.println(count++ + "BeanPostProcessor-> postProcessAfterInitialization...");
// 在 Bean 初始化之后添加逻辑
return bean; // 返回原始或修改后的 Bean
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
System.out.println(count++ + "BeanFactoryAware-> setBeanFactory...");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println(count++ + "InitializingBean-> afterPropertiesSet...");
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println(count++ + "ApplicationContext-> setApplicationContext...");
}
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println(count++ + "ApplicationRunner-> run...");
}
}