SpringBoot @ComponentScan掃描的局限性方式
SpringBoot @ComponentScan掃描的局限性
使用@ComponentScan注解時,Spring只注入設置的類或者包及包的子集對象。
這會導致原來@SpringBootApplication 自動配置裝配的功能在對象注入的時候不會注入當前工程。
@ComponentScan
掃描依賴注入模塊服務 [注意本項目的掃描@ComponentScan必須手動加入當前項目的包掃描路徑]
package com.patrol.mobile;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* 開啟異步請求
*/
@EnableAsync
/**
* 開啟接口緩存
*/
@EnableCaching
/**
* 開啟定時任務調度
*/
@EnableScheduling
/**
* 開啟接口文檔描述
*/
@EnableSwagger2
/**
* 掃描依賴注入模塊服務[注意本項目的掃描@ComponentScan必須手動加入當前項目的包掃描路徑]
*/
@ComponentScan(basePackages = {"com.patrol.config", "com.patrol.web", "com.patrol.position.service", "com.patrol.mobile"})
/**
* @SpringBootApplication 相當于@Configuration,@EnableAutoConfiguration和 @ComponentScan 并具有他們的默認屬性值
*/
@SpringBootApplication
public class PatrolMobileServiceApplication {
public static void main(String[] args) {
SpringApplication.run(PatrolMobileServiceApplication.class, args);
}
}@ComponentScan的局限性很明顯,只掃描配置的這些包或者類。
使用@SpringbootApplication注解
可以解決根類或者配置類(我自己的說法,就是main所在類)頭上注解過多的問題,一個@SpringbootApplication相當于@Configuration,@EnableAutoConfiguration 和 @ComponentScan 并具有他們的默認屬性值。
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
關于Java Guava ImmutableMap不可變集合源碼分析
這篇文章主要介紹Java Guava不可變集合ImmutableMap的源碼分析的相關資料,需要的朋友可以參考下面具體的文章內容2021-09-09
Spring Boot的Maven插件Spring Boot Maven plu
Spring Boot的Maven插件Spring Boot Maven plugin以Maven的方式提供Spring Boot支持,Spring Boot Maven plugin將Spring Boot應用打包為可執(zhí)行的jar或war文件,然后以通常的方式運行Spring Boot應用,本文介紹Spring Boot的Maven插件Spring Boot Maven plugin,一起看看吧2024-01-01

