好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

SpringBoot中@ComponentScan的使用详解

SpringBoot @ComponentScan的使用

SpringBoot的启动类中有一个@ComponentScan,之前项目由于这个注解造成打包失败,这里对于这个注解进行总结,防止下次遇到这个问题再被难住。

其实这个注解主要是针对于第三方jar包中注解的应用。

如果第三方包中没有使用注解那么就完全不需要使用这个注解

使用方式如图所示,这里扫描的是

maven项目的依赖包中的ins目录下的组件

如果是直接引用项目

那么就要引用这个项目代码的根路径,一般公司会命名为[cn]

SpringBoot @ComponentScan 作用

SpringBoot在写启动类的时候如果不使用@ComponentScan指明对象扫描范围,默认指扫描当前启动类所在的包里的对象,如果当前启动类没有包,则在启动时会报错:

Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package错误

因为启动类不能直接放在main/java文件夹下,必须要建一个包把它放进去或者使用@ComponentScan指明要扫描的包。代码示例如下:

?

1

2

3

4

5

6

7

@SpringBootApplication

@ComponentScan (basePackageClasses=MytestApplication. class )

public class MytestApplication {

     public static void main(String[] args){

         SpringApplication.run(MytestApplication. class , args);

     }

}

@ComponentScan(basePackageClasses=要扫描类.class所在位置的包)-意思是要扫描哪个类所在的包

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/wenyan_liu/article/details/80864134

查看更多关于SpringBoot中@ComponentScan的使用详解的详细内容...

  阅读:17次