Spring的接口InitializingBean、BeanPostProcessor以及注解@PostConstruct、bean的init-method的执行先后顺序

2023-05-16

InitializingBean

    InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候都会执行该方法。

public class MyServiceImpl implements MyService, InitializingBean {

	@Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("AfterPropertiesSet method: myServiceImpl");
    }
}

BeanPostProcessor

    BeanPostProcessor接口提供了初始化bean时的前置接口和后置接口,我们只需要实现BeanPostProcessor中对应的接口就可以bean初始化前后做自己的逻辑处理。(BeanPostProcessor的前置和后置方法会在每个bean初始化的时候调用,个人不推荐使用)

@Component
public class MyCustomBeanPostProcessor implements BeanPostProcessor {

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    System.out.println("BeanPostProcessor Before init: " + beanName);
    return bean;
}

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    System.out.println("BeanPostProcessor after init: " + beanName);
    return bean;
}

}


@PostConstruct

    在类中的方法上加上注解@PostConstruct后,初始化bean的前会调用被注解的方法

@Service
public class MyServiceImpl implements MyService{

	@PostConstruct
    public void postConstructMethod() {
        System.out.println("Post construct method: myServiceImpl");
    }
}

    那么问题来了,这些方法以及bean的init-method在初始化bean的时候,执行的先后顺序是怎样,做个测试便知道了,把上面的MyServiceImpl合到一起,并且上面定义的MyCustomBeanPostProcessor。MyServiceImpl类最终如下:

@Service
public class MyServiceImpl implements MyService, InitializingBean {

    @PostConstruct
    public void postConstructMethod() {
        System.out.println("Post construct method: myServiceImpl");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("AfterPropertiesSet method: myServiceImpl");
    }

    public void initMethod() {
        System.out.println("Init method: myServiceImpl");
    }

使用Junit测试得到的输出结果如下:

BeanPostProcessor Before init: myServiceImpl
Post construct method: myServiceImpl
AfterPropertiesSet method: myServiceImpl
Init method: myServiceImpl
BeanPostProcessor after init: myServiceImpl

由此可见初始化Bean的先后顺序为

  • BeanPostProcessor的postProcessBeforeInitialization方法
  • 类中添加了注解@PostConstruct 的方法
  • InitializingBean的afterPropertiesSet方法
  • bean的指定的初始化方法: init-method
  • BeanPostProcessor的postProcessAftrInitialization方法

至于为什么会是这个顺序,暂时没有深入研究,感兴趣的可以深入研究Spring源码。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring的接口InitializingBean、BeanPostProcessor以及注解@PostConstruct、bean的init-method的执行先后顺序 的相关文章

随机推荐