SpringBoot中@ComponentScan的使⽤详解
⽬录
SpringBoot @ComponentScan的使⽤
SpringBoot @ComponentScan 作⽤
SpringBoot @ComponentScan的使⽤
SpringBoot的启动类中有⼀个@ComponentScan,之前项⽬由于这个注解造成打包失败,这⾥对于这个注解进⾏总结,防⽌下次遇到这个问题再被难住。
其实这个注解主要是针对于第三⽅jar包中注解的应⽤。
如果第三⽅包中没有使⽤注解那么就完全不需要使⽤这个注解
使⽤⽅式如图所⽰,这⾥扫描的是
maven项⽬的依赖包中的ins⽬录下的组件springboot其实就是spring
如果是直接引⽤项⽬
那么就要引⽤这个项⽬代码的根路径,⼀般公司会命名为“cn”
SpringBoot @ComponentScan 作⽤
SpringBoot在写启动类的时候如果不使⽤@ComponentScan指明对象扫描范围,默认指扫描当前启动类所在的包⾥的对象,如果当前启动类没有包,则在启动时会报错:
Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package错误
因为启动类不能直接放在main/java⽂件夹下,必须要建⼀个包把它放进去或者使⽤@ComponentScan指明要扫描的包。代码⽰例如下:
@SpringBootApplication
@ComponentScan(basePackageClasses=MytestApplication.class)
public class MytestApplication {
public static void main(String[] args){
SpringApplication.run(MytestApplication.class, args);
}
}
@ComponentScan(basePackageClasses=要扫描类.class所在位置的包)-意思是要扫描哪个类所在的包
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。

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