小编给大家分享一下SpringBoot项目启动时读取配置以及初始化资源的方法,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨方法吧!
介绍
  在开发过程中,我们有时候会遇到非接口调用而出发程序执行任务的一些场景,比如我们使用quartz定时框架通过配置文件来启动定时任务时,或者一些初始化资源场景等触发的任务执行场景。
方法一:注解
方案
  通过使用注解@Configuration和@Bean来初始化资源,配置文件当然还是通过@Value进行注入。
补充@Configuration加载Spring:
示例
package com.example.andya.demo.conf;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author andya
* @create 2020-06-24 14:37
*/
@Configuration
public class InitConfigTest {
@Value("${key}")
private String key;
@Bean
public String testInit(){
System.out.println("init key: " + key);
return key;
}
}
方法二:CommandLineRunner
方案
  实现CommandLineRunner接口,该接口中的Component会在所有Spring的Beans都初始化之后,在SpringApplication的run()之前执行。
  多个类需要有顺序的初始化资源时,我们还可以通过类注解@Order(n)进行优先级控制
示例
package com.example.andya.demo.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
/**
* @author andya
* @create 2020-06-24 14:47
*/
@Component
public class CommandLineRunnerTest implements CommandLineRunner {
@Value("${key}")
private String key;
@Override
public void run(String... strings) throws Exception {
System.out.println("command line runner, init key: " + key);
}
}
两个示例的运行结果
看完了这篇文章,相信你对SpringBoot项目启动时读取配置以及初始化资源的方法有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。