iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >springboot启动前执行方法的四种方式总结
  • 481
分享到

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

2024-04-02 19:04:59 481人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

目录第一种  @PostConstruct注解第二种  实现InitializingBean接口第三种 实现BeanPostProcessor接口第四种 &nbs

第一种  @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) {
        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维护的对象调用前后做操作,具体可以参照这篇博文

www.jb51.net/article/234143.htm

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

总结

到此这篇关于springboot启动前执行方法的四种方式的文章就介绍到这了,更多相关springboot启动前执行方法内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: springboot启动前执行方法的四种方式总结

本文链接: https://www.lsjlt.com/news/162038.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作