在开发过程中,我们有时候会遇到非接口调用而出发程序执行任务的一些场景,比如我们使用 quartz 定时框架通过配置文件来启动定时任务时,或者一些初始化资源场景等触发的任务执行场景。
通过使用注解 @Configuration 和 @Bean 来初始化资源,配置文件当然还是通过 @Value 进行注入。
@Bean 注解的方法。 AnnotationConfigApplicationContext 或者 AnnotationConfgWebApplicationContext 扫描,用于构建bean定义,从而初始化Spring容器。产生这个对象的方法Spring只会调用一次,之后Spring就会将这个Bean对象放入自己的Ioc容器中。 补充@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 接口,该接口中的 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);
}
}