SpringBoot @ComponentScan扫描的局限性方式
作者:boonya
文章总结:SpringBoot的@ComponentScan注解在扫描组件时存在局限性,只能扫描指定的包及其子包,无法扫描@SpringBootApplication注解自动配置的组件,使用@SpringBootApplication注解可以解决这一问题,它集成了@Configuration、@EnableAutoConfiguration
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 并具有他们的默认属性值。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。