直接上结论(已经过代码测试验证)
如果是在同一个类中,也就是这个类既实现了接口ApplicationContextAware又有用了注解PostConstruct的方法,那么在这个类中setApplicationContext方法会先执行,PostConstruct注解的方法会后执行。
@Component
public class ApplicationContextUtils implements ApplicationContextAware {
static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("ApplicationContextUtils---setApplicationContext执行了------");
context = applicationContext;
}
@PostConstruct
protected void createMessageContentHandlerChain() {
System.out.println("ApplicationContextUtils---postConstruct执行了---------");
}
public static Object getBeanByName(String beanName) {
return context.getBean(beanName);
}
}
如果是在不同的类中,注意:这些类之间没有依赖关系,那么spring会按照bean注册的顺序执行这些类里的setApplicationContext/@PostConstruct方法。也就是说哪个类在上面就会先被spring注册,那么这个类的setApplicationContext/@PostConstruct方法就会先执行。
**说白了就是spring是初始化完一个bean再去初始化另一个bean;所以下面扩展一下这些bean得BeanPostProcessor接口里的方法的执行顺序是怎么样的呢?**直接上图
@Component
public class BeanPostProcessUtil implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if(bean instanceof MessageContentHandlerChain){
System.out.println(beanName+"--postProcessBeforeInitialization执行了---------");
}
return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if(bean instanceof MessageContentHandlerChain){
System.out.println(beanName+"--postProcessAfterInitialization---------");
}
return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
}
}
对于同一个bean,那么它的postProcessBeforeInitialization会先执行,然后是这个bean里的@PostConstruct方法会接着执行,最后是postProcessAfterInitialization方法执行;对于不同的bean则是spring先注册哪个bean会把这个bean的postProcessBeforeInitialization、@PostConstruct和postProcessAfterInitialization依次执行完才会去初始化下一个bean。