springboot應用中使用CommandLineRunner


在springboot應用中,存在這樣的使用場景,在springboot ioc容器創建好之后根據業務需求先執行一些操作,springboot提供了兩個接口可以實現該功能:

  1. CommandLineRunner
  2. ApplicatioinRunner

使用思路:

  1. 實現改接口,重寫run方法,run方法中完成要完成的操作
  2. 實例化接口,並注入到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");
	}
}

總結

  1. @SpringBootApplication標注的類是一個配置類
  2. 在springboot應用中,配置類對象會自動被spring ioc容器所管理
  3. 在測試類中,使用AnnotationConfigApplicationContext獲取容器對象,發現無法獲取,說明在非springboot項目中,被@Configuration標注的類不會對項目進行自動配置,必須要添加配置參數。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM