spring探秘:通过BeanPostProcessor、@PostConstruct、InitializingBean在启动前执行方法
作者:互联网
spring探秘:通过BeanPostProcessor、@PostConstruct、InitializingBean在启动前执行方法
springboot启动前执行方法的3种方式:实现BeanPostProcessor接口、实现InitializingBean接口、使用@PostConstruct注解
示例:
第一种 实现BeanPostProcessor接口
@Configuration public class Test3 implements BeanPostProcessor { @Autowired private Environment environment;
@Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { String property = environment.getProperty("aaa.bbb"); System.out.println("test3"+property); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; }
}
第二种 实现InitializingBean接口
@Configuration
public class Test2 implements InitializingBean {
@Autowired
private Environment environment;
@Override
public void afterPropertiesSet() throws Exception {
String property = environment.getProperty("aaa.bbb");
System.out.println("test2"+property);
}
}
第三种 使用@PostConstruct注解
@Configuration
public class Test1 {
@Autowired
private Environment environment;
@PostConstruct
public void test(){
String property = environment.getProperty("aaa.bbb");
System.out.println("test1"+property);
}
}
运行的优先级是:
启动类前->BeanPostProcessor->@PostConstruct->InitializingBean
需注意:BeanPostProcessor的方式会让实现类里的方法提前执行。BeanPostProcessor为每一个spring维护的对象调用前后做操作,实现了它我们当前类就会变成一个BeanPostProcessor对象,就可以像BeanPostProcessor一样在容器加载最初的几个阶段被实例化,只要被实例化,PostConstruct注解的标注的方法就会立即执行。
参考:https://www.jianshu.com/p/1845fe64decd
https://www.jianshu.com/p/1417eefd2ab1
标签:InitializingBean,BeanPostProcessor,spring,PostConstruct,environment,property,pub 来源: https://www.cnblogs.com/kelelipeng/p/16113847.html