介紹
在開發過程中,我們有時候會遇到非接口調用而出發程序執行任務的一些場景,比如我們使用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);
}
}