SpringBoot默认包扫描机制及@ComponentScan指定扫描路径详解SpringBoot默认包扫描机制及@ComponentScan指定扫描路径详解
SpringBoot默认包扫描机制
标注了@Component和@Component的衍⽣注解如@Controller,@Service,@Repository就可以把当前的Bean加⼊到IOC容器中。那么SpringBoot是如何知道要去扫描@Component注解的呢。@ComponentScan做的事情就是告诉Spring从哪⾥到bean
SpringBoot默认包扫描机制: 从启动类所在包开始,扫描当前包及其⼦级包下的所有⽂件。我们可以通过以下的测试来验证⼀下。
启动应⽤并访问BannerController这个控制器,⽬录结构如图
访问结果正常
当把BannerController移动到上⼀级⽬录,应⽤可以正常启动
但是再次访问刚才的路径时却出现了如下错误,代码是没有变动的,是Controller扫描 不到了。
实际上SpringBoot是通过@ComponentScan进⾏扫描。默认情况下,⼊⼝类上⾯的@SpringBootApplication⾥⾯有⼀个@ComponentScan,也就相当于@ComponentScan标注在⼊⼝类上。
所以默认情况下,扫描⼊⼝类同级及其⼦级包下的所有⽂件。当我们想⾃⼰制定包扫描路径就需要加⼀个@ComponentScan @ComponentScan的使⽤
常⽤参数含义
basePackages与value: ⽤于指定包的路径,进⾏扫描(默认参数)
basePackageClasses: ⽤于指定某个类的包的路径进⾏扫描
includeFilters: 包含的过滤条件
FilterType.ANNOTATION:按照注解过滤
FilterType.ASSIGNABLE_TYPE:按照给定的类型
FilterType.ASPECTJ:使⽤ASPECTJ表达式
FilterType.REGEX:正则
FilterType.CUSTOM:⾃定义规则
excludeFilters: 排除的过滤条件,⽤法和includeFilters⼀样
nameGenerator: bean的名称的⽣成器
useDefaultFilters: 是否开启对@Component,@Repository,@Service,@Controller的类进⾏检测
指定要扫描的包
上述例⼦,如果想扫描启动类上⼀级包,使⽤@ComponentScan指定包扫描路径,即可将BannerController加⼊到容器
@SpringBootApplication
@ComponentScan("com.lin")
public class MissyouApplication {
public static void main(String[] args){
SpringApplication.run(MissyouApplication.class, args);
}
}
excludeFilters 排除某些包的扫描
测试类准备:
@Controller
public class BannerController {
BannerController(){
System.out.println("Hello BannerController");
}
}
--------------------------------------------------------------------
@Service
public class TestService {
TestService(){
System.out.println("Hello TestService");
}
}
⽬录结构如下:
启动类上加@ComponentScan指定扫描lin这个包并排除@Controller这个注解标注的类
@SpringBootApplication
@ComponentScan(value ="com.lin",
excludeFilters ={@ComponentScan.Filter(type = FilterType.ANNOTATION,value ={Controller.class})})
public class MissyouApplication {
public static void main(String[] args){
SpringApplication.run(MissyouApplication.class, args);
}
}
启动应⽤,控制台打印出了TestService⽽没有BannerController
@Component与@ComponentScan
在某个类上使⽤@Component注解,表明当需要创建类时,这个被注解标注的类是⼀个候选类。就像是有同学在举⼿。@ComponentScan ⽤于扫描指定包下的类。就像看都有哪些举⼿了。
springboot多模块包扫描问题的解决⽅法
spring ioc注解
问题描述:
springboot建⽴多个模块,当⼀个模块需要使⽤另⼀个模块的服务时,需要注⼊另⼀个模块的组件,如下⾯图中例⼦:
memberservice模块中的MemberServiceApiImpl类需要注⼊common模块中的RedisService组件,该怎么注⼊呢?
解决:
在memberservice模块的启动类上加上RedisService类所在包的全路径的组件扫描,就像这样:
注意启动类上⽅的注解@ComponentScan(basePackages={“dis”}),这⼀句实际上就已经加上了RedisService的组件扫描,但是这样做是有问题的,我发现启动后服务不能正常访问。查资料后发现是因为@ComponentScan 和
@SpringBootApplication注解的包扫描有冲突,@ComponentScan注解包扫描会覆盖掉@SpringBootApplication的包扫描。解决办法就是在@ComponentScan(basePackages={“dis”})的基础上加上@SpringBootApplication扫描的包,那么@SpringBootApplication扫描了哪些包呢?实际上,它默认扫描的是启动类所在的包及其⼦包,所以我的例⼦上需要改成
@ComponentScan(basePackages={“dis”,“berservice”}). OK ,结束!!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。