zoukankan      html  css  js  c++  java
  • Spring Boot中初始化资源的几种方式

    CommandLineRunner

    • 定义初始化类 MyCommandLineRunner
    • 实现 CommandLineRunner接口,并实现它的 run()方法,在该方法中编写初始化逻辑
    • 注册成Bean,添加 @Component注解即可
    • 示例代码如下:
    @Component
    public class MyCommandLineRunner implements CommandLineRunner {
    
        @Override
        public void run(String... args) throws Exception {
            System.out.println("...init resources by implements CommandLineRunner");
        }
        
    }
    

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




    ApplicationRunner

    • 定义初始化类 MyApplicationRunner
    • 实现 ApplicationRunner接口,并实现它的 run()方法,在该方法中编写初始化逻辑
    • 注册成Bean,添加 @Component注解即可
    • 示例代码如下:
    @Component
    public class MyApplicationRunner implements ApplicationRunner {
    
        @Override
        public void run(ApplicationArguments applicationArguments) throws Exception {
            System.out.println("...init resources by implements ApplicationRunner");
        }
    
    }
    

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




    @PostConstruct 

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

  • 相关阅读:
    [Python]机器学习:Tensorflow实现线性回归
    Python之Numpy:线性代数/矩阵运算
    特殊环境的安装教程[汇总]
    C/C++之编程语言学习资源
    Python之文件操作工具
    NLP之中文自然语言处理工具库:SnowNLP(情感分析/分词/自动摘要)
    网络分析:WireShark
    Linux/Window之定时任务脚本编写
    CSS之Background
    JavaScript之iframe页面间通信
  • 原文地址:https://www.cnblogs.com/zhangfengshi/p/9548151.html
Copyright © 2011-2022 走看看