springboot启动前执行方法的四种方式总结

网友投稿 271 2022-11-09

springboot启动前执行方法的四种方式总结

目录第一种  @PostConstruct注解第二种  实现InitializingBean接口第三种 实现BeanPostProcessor接口第四种  在启动类run之前执行方法总结

第一种  @PostConstruct注解

@Configuration

public class Test1 {

@Autowired

private Environment environment;

@PostConstruct

public void test(){

String property = environment.getProperty("aaa.bbb");

System.out.println("test1"+property);

}

}

第二种  实现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);

}

}

第三种 实现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;

}

}

第四种  在启动类run之前执行方法

@SpringBootApplication

public class DemoApplication {

public static void main(String[] args) {

http:// System.out.println("test4");

SpringApplication.run(DemoApplication.class, args);

}

}

当然这是不可取的

他们运行的优先级是

启动类前->BeanPostProcessor->@PostConstruct->InitializingBean

值得注意的是第三种方式,他可以让实现类里的方法提前执行

同样的使用@PostConstruct的两个类

@Configuration

public class Test1 {

@PostConstruct

public void test(){

System.out.println("test1");

}

}

第一个没有实现BeanPostProcessor接口

@Configuration

public class Test3 implements BeanPostProcessor {

@Autowired

private Environment environment;

@PostConstruct

public void test(){

System.out.println("test3");

}

}

第二个实现了BeanPostProcessor接口,但是没有重写他的方法

打印结果如下

可以看到同样是使用了@PostConstruct注解,但是他们的执行顺序却截然不同

BeanPostProcessor为每一个spring维护的对象调用前后做操作,具体可以参照这篇博文

https://jianshu.com/p/1417eefd2ab1

知道了启动时的加载顺序,对http://我们做一些初始化工作有帮助。

总结

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:istio 常见的 10 个异常
下一篇:美国正在开发用于图处理的下一代ASIC
相关文章

 发表评论

暂时没有评论,来抢沙发吧~