软件编程
位置:首页>> 软件编程>> java编程>> SpringBoot中@ComponentScan的使用详解

SpringBoot中@ComponentScan的使用详解

作者:终身编号9527  发布时间:2023-07-14 06:19:22 

标签:SpringBoot,@ComponentScan

SpringBoot @ComponentScan的使用

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

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

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

SpringBoot中@ComponentScan的使用详解

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

SpringBoot中@ComponentScan的使用详解

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

如果是直接引用项目

SpringBoot中@ComponentScan的使用详解

那么就要引用这个项目代码的根路径,一般公司会命名为“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所在位置的包)-意思是要扫描哪个类所在的包

来源:https://blog.csdn.net/wenyan_liu/article/details/80864134

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com