标签:token object bsp oid 执行 容器 str shu opera
springboot启动前执行方法的3种方式:实现BeanPostProcessor接口、实现InitializingBean接口、使用@PostConstruct注解
示例:
@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; }
}
@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);
}
}
@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注解的标注的方法就会立即执行。
spring探秘:通过BeanPostProcessor、@PostConstruct、InitializingBean在启动前执行方法
标签:token object bsp oid 执行 容器 str shu opera
原文地址:https://www.cnblogs.com/feng-gamer/p/12001205.html