介绍
在开发过程中,我们有时候会遇到非接口调用而出发程序执行任务的一些场景,比如我们使用 quartz
定时框架通过配置文件来启动定时任务时,或者一些初始化资源场景等触发的任务执行场景。
方法一:注解
方案
通过使用注解 @Configuration
和 @Bean
来初始化资源,配置文件当然还是通过 @Value
进行注入。
- @Configuration:用于定义配置类,可替换xml配置文件,被注解的类内部一般是包含了一个或者多个
@Bean
注解的方法。 - @Bean:产生一个Bean对象,然后将Bean对象交给Spring管理,被注解的方法是会被
AnnotationConfigApplicationContext
或者AnnotationConfgWebApplicationContext
扫描,用于构建bean定义,从而初始化Spring容器。产生这个对象的方法Spring只会调用一次,之后Spring就会将这个Bean对象放入自己的Ioc容器中。
补充@Configuration加载Spring:
- @Configuration配置spring并启动spring容器
- @Configuration启动容器+@Bean注册Bean
- @Configuration启动容器+@Component注册Bean
- 使用 AnnotationConfigApplicationContext 注册 AppContext 类的两种方法
- 配置Web应用程序(web.xml中配置AnnotationConfigApplicationContext)
示例
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);
}
}
两个示例的运行结果
原文
http://www.cnblogs.com/Andya/p/13187845.html
本站部分文章源于互联网,本着传播知识、有益学习和研究的目的进行的转载,为网友免费提供。如有著作权人或出版方提出异议,本站将立即删除。如果您对文章转载有任何疑问请告之我们,以便我们及时纠正。PS:推荐一个微信公众号: askHarries 或者qq群:474807195,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

转载请注明原文出处:Harries Blog™ » SpringBoot——项目启动时读取配置及初始化资源