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 并具有他们的默认属性值。

 

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