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 並具有他們的默認屬性值。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章