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 并具有他们的默认属性值。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
SpringBoot工程Docker多环境中使用同一个Jar包解决方案
在Docker多环境部署中,SpringBoot工程可以通过环境变量来动态改变配置,无需重新打包,利用volume挂载或docker cp命令,可以将配置文件直接传入容器,提高部署效率,并保证安全性2024-09-09
springmvc字符编码过滤器CharacterEncodingFilter的使用
这篇文章主要介绍了springmvc字符编码过滤器CharacterEncodingFilter的使用,具有很好的参考价值,希望对大家有所帮助。2021-08-08
解决Nacos成功启动但是无法访问 (Connection refused)
这篇文章主要介绍了解决Nacos成功启动但是无法访问 (Connection refused)问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2024-06-06


最新评论