Spring Boot 中初始化资源的方式,你知道几种?

淡淡的烟草味﹌ 2022-09-04 10:40 433阅读 0赞

假设有这么一个需求,要求在项目启动过程中,完成线程池的初始化,加密证书加载等功能,你会怎么做?如果没想好答案,请接着往下看。今天介绍几种在Spring Boot中进行资源初始化的方式,帮助大家解决和回答这个问题。

CommandLineRunner

  • 定义初始化类 MyCommandLineRunner
  • 实现 CommandLineRunner 接口,并实现它的 run() 方法,在该方法中编写初始化逻辑
  • 注册成Bean,添加 @Component注解即可
  • 示例代码如下:

    package cn.zh.controller;

    import org.springframework.boot.CommandLineRunner;
    import org.springframework.core.annotation.Order;
    import org.springframework.stereotype.Component;

    @Componentpublic class MyCommandLineRunner implements CommandLineRunner {

    1. @Override
    2. public void run(String... args) throws Exception {
    3. System.out.println("项目初始化---------------11");
    4. }

    }

实现了 CommandLineRunner 接口的 Component 会在所有 Spring Beans 初始化完成之后, 在 SpringApplication.run() 执行之前完成。下面通过加两行打印来验证我们的测试。

  1. package cn.zh;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class ProcApplication {
  6. public static void main(String[] args) {
  7. System.out.println("...start SpringApplication.run");
  8. SpringApplication.run(ProcApplication.class,args);
  9. System.out.println("....end SpringApplication.run");
  10. }
  11. }

91615d5a596cc2a13adac4aa66ba8f4c.png

ApplicationRunner

  • 定义初始化类 MyApplicationRunner
  • 实现 ApplicationRunner 接口,并实现它的 run() 方法,在该方法中编写初始化逻辑
  • 注册成Bean,添加 @Component注解即可
  • 示例代码如下:

    package cn.zh.controller;

    import org.springframework.boot.ApplicationArguments;
    import org.springframework.boot.ApplicationRunner;
    import org.springframework.core.annotation.Order;
    import org.springframework.stereotype.Component;

    import javax.annotation.PostConstruct;

    @Component
    public class MyApplicationRunner implements ApplicationRunner {

    1. @Override
    2. public void run(ApplicationArguments args) throws Exception {
    3. System.out.println("项目初始化二---------");
    4. }
  1. }

可以看到,通过实现 ApplicationRunner 接口,和通过实现 CommandLineRunner 接口都可以完成项目的初始化操作,实现相同的效果。两者之间唯一的区别是 run() 方法中自带的形参不相同,在 CommandLineRunner 中只是简单的String... args形参,而 ApplicationRunner 则是包含了 ApplicationArguments 对象,可以帮助获得更丰富的项目信息。

c823705cbc2ff971ea0d200b75d75309.png

@Order

如果项目中既有实现了 ApplicationRunner 接口的初始化类,又有实现了 CommandLineRunner 接口的初始化类,那么会是哪一个先执行呢?测试告诉我们,答案是实现了 ApplicationRunner 接口的初始化类先执行,我想这点倒是不需要大家过分去关注为什么。但如果需要改变两个初始化类之间的默认执行顺序,那么使用 @Order 注解就可以帮助我们解决这个问题。

210995b9ff1094236f2964bdbd5dca93.png

  1. @Component
  2. @Order(1)
  3. public class MyCommandLineRunner implements CommandLineRunner {
  4. /**
  5. * Callback used to run the bean.
  6. *
  7. * @param args incoming main method arguments
  8. * @throws Exception on error
  9. */
  10. @Override
  11. public void run(String... args) throws Exception {
  12. System.out.println("项目初始化---------------11");
  13. }
  14. }
  15. @Component
  16. @Order(2)
  17. public class MyApplicationRunner implements ApplicationRunner {
  18. @Override
  19. public void run(ApplicationArguments args) throws Exception {
  20. System.out.println("项目初始化二---------");
  21. }
  22. @PostConstruct
  23. public void init(){
  24. System.out.println("@PostConstruct初始化");
  25. }
  26. }

0e0170dd6dfba4896a56717f8cb49ec9.png 65540d3deb68040de4cb67ac03883c59.png 329daf4ad9d330fcd5e9cd70966089da.png

@PostConstruct

使用 @PostConstruct 注解同样可以帮助我们完成资源的初始化操作,前提是这些初始化操作不需要依赖于其它Spring beans的初始化工作。

8aa08d483e1f7899efcc17d760d901ae.png

可以看到 @PostConstruct 注解是用在方法上的,写一个方法测试一下吧。

  1. @PostConstruct
  2. public void init(){
  3. System.out.println("@PostConstruct初始化");
  4. }
  • 注意:
    • 只有一个非静态方法能使用此注解
    • 被注解的方法不得有任何参数
    • 被注解的方法返回值必须为void
    • 被注解方法不得抛出已检查异常
    • 此方法只会被执行一次
  • 综上,使用 @PostConstruct 注解进行初始化操作的顺序是最快的,前提是这些操作不能依赖于其它Bean的初始化完成。通过添加 @Order 注解,我们可以改变同层级之间不同Bean的加载顺序。

InitializingBean

InitializingBean 是 Spring 提供的一个接口,只包含一个方法 afterPropertiesSet()。凡是实现了该接口的类,当其对应的 Bean 交由 Spring 管理后,当其必要的属性全部设置完成后,Spring 会调用该 Bean 的 afterPropertiesSet()。

  1. @Component
  2. public class MyListener1 implements InitializingBean {
  3. @Autowired
  4. private ShopInfoMapper shopInfoMapper;
  5. @Override
  6. public void afterPropertiesSet() {
  7. //使用spring容器中的bean
  8. //System.out.println(shopInfoMapper.selectById("1").getShopName());
  9. System.out.println("项目启动OK");
  10. }
  11. }

ApplicationListener

ApplicationListener 就是spring的监听器,能够用来监听事件,典型的观察者模式。如果容器中有一个ApplicationListener Bean,每当ApplicationContext发布ApplicationEvent时,ApplicationListener Bean将自动被触发。这种事件机制都必须需要程序显示的触发。

其中spring有一些内置的事件,当完成某种操作时会发出某些事件动作。比如监听ContextRefreshedEvent事件,当所有的bean都初始化完成并被成功装载后会触发该事件,实现ApplicationListener接口可以收到监听动作,然后可以写自己的逻辑。

同样事件可以自定义、监听也可以自定义,完全根据自己的业务逻辑来处理。所以也能做到资源的初始化加载。

  1. @Component
  2. public class MyListener1 implements ApplicationListener {
  3. @Override
  4. public void onApplicationEvent(ApplicationEvent applicationEvent) {
  5. //打印出每次事件的名称
  6. System.out.println(applicationEvent.toString());
  7. if (applicationEvent instanceof ApplicationReadyEvent) {
  8. System.out.println("项目启动OK");
  9. }
  10. }
  11. }

6e900479f4cef1ecdea4f4ee090ebe95.png

(完)

源于:cnblogs.com/zouhong/p/14415713.html

  1. 1. SQL语法速成手册,建议收藏!2. 后端接口如何提高性能?3. Redis中主、从库宕机如何恢复?4. 面试必备:聊聊数据库中的事务和锁5. 这次专治Docker疑难杂症6. 这三种单点登录的方式你都Get吗?
  2. PS:如果觉得我的分享不错,欢迎大家随手点赞、在看。
  3. ▽加我微信,交个朋友
  4. 长按/扫码添加↑↑↑
  5. 看完本文有收获?请转发分享给更多人请长按二维码,关注 Java大数据修炼之道.推荐程序员必备公众号
  6. Java大数据修炼之道公众号:gh_9119f24d3793
  7. 推荐理由:在这里,我们分享程序员相关技术,职场生活,行业热点资讯。不定期还会分享IT趣文和趣图。这里属于我们程序员自己的生活,工作和娱乐空间。 ▼长按下方↓↓↓二维码识别关注关注 java大数据修炼之道 每天学习java技术你想学的Java知识这里都有点「在看」的人都涨薪了哦

发表评论

表情:
评论列表 (有 0 条评论,433人围观)

还没有评论,来说两句吧...

相关阅读

    相关 异步编程方式,知道?

    异步执行对于开发者来说并不陌生,在实际的开发过程中,很多场景多会使用到异步,相比同步执行,异步可以大大缩短请求链路耗时时间。 比如:`「发送短信、邮件、异步更新等」`,这些都