在springboot應用中,存在這樣的使用場景,在springboot ioc容器創建好之后根據業務需求先執行一些操作,springboot提供了兩個接口可以實現該功能:
- CommandLineRunner
- ApplicatioinRunner
使用思路:
- 實現改接口,重寫run方法,run方法中完成要完成的操作
- 實例化接口,並注入到spring ioc容器
/**
* Application類
*/
@SpringBootApplication
public class Application implements CommandLineRunner {
@Resource
private HelloService helloService;
public static void main(String[] args) {
System.out.println(" 容器創建之前");
SpringApplication.run(Application.class, args);
System.out.println("容器創建之后");
}
@Override
public void run(String... args) throws Exception {
System.out.println("前面過程在創建容器,現在創建好了,先執行下列操作:");
//調用run方法時,spring ioc容器中helloService已經創建並裝配好
helloService.sayHello("操作:arminker");
}
}
總結:
- @SpringBootApplication標注的類是一個配置類
- 在springboot應用中,配置類對象會自動被spring ioc容器所管理
- 在測試類中,使用AnnotationConfigApplicationContext獲取容器對象,發現無法獲取,說明在非springboot項目中,被@Configuration標注的類不會對項目進行自動配置,必須要添加配置參數。