Spring Boot的Component Scan原理

26 篇文章 0 订阅
7 篇文章 0 订阅

@ComponentScan

如果你了解组件扫描,你就会理解Spring。Spring是一个依赖注入框架。它完全是关于依赖的bean和wiring。

定义Spring Beans的第一步是添加正确的注释 - @Component或@Service或@Repository。但是,Spring不知道bean在哪个包下面,除非你告诉它去哪里搜索包。

这部分“告诉Spring到哪里搜索”称为组件扫描。

你必须定义了需要扫描的包,为包定义组件扫描后,Spring将搜索包及其所有子包以获取组件/ bean。

下面展示了如何进行组件扫描的定义:

 

Spring Boot项目中的组件扫描

 

  • 如果你的其他包层次结构位于使用@SpringBootApplication标注主应用程序下方,则隐式组件扫描将自动涵盖。也就是说,不要明确标注@ComponentScan,Spring Boot会自动搜索当前应用主入口目录及其下方子目录。
  • 如果其他包中的bean /组件不在当前主包路径下面,,则应手动使用@ComponentScan 添加
  • 如果使用了@ComponentScan ,那么Spring Boot就全部依赖你的定义,如果定义出错,会出现autowired时出错,报a bean of type that could not be found错误,让你很恼火哦。

#######详细示例

考虑下面:

package com.jdon.springboot

@SpringBootApplication
public class MyApplication {

   public static void main(String[] args) {
      SpringApplication.run(MyApplication.class, args);
   }
}

@SpringBootApplication定义在MyApplication这个类上面,而这个类在包com.jdon.springboot下面。

@SpringBootApplication定义了对包com.jdon.springboot进行自动组件扫描。

如果所有组件都在上述包或其子包中定义,则一切正常。

但是,假设其中一个组件是在包中定义的 com.jdon.springboot2下,在这种情况下,需要将新包添加到组件扫描中。

两个选项

  • 定义@ComponentScan(“com.jdon.springboot2”)
    • 这将扫描com.jdon.springboot2的整个父树。
  • 或者使用数组定义两个特定的组件扫描。
    • @ComponentScan({“com.jdon.springboot2.abc”,”com.jdon.springboot2.efg”})

 

 

  #### No qualifying bean of type found  

No qualifying bean of type [com.jdon.springboot.jpa.UserRepository] found for dependency [com.jdon.springboot.jpa.UserRepository]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

或在Intellij Idea中显示 incorrectly saying no beans of type found for autowired repository

```

上述两个问题的根本原因相同 - 组件未被Spring boot发现。

你需要检查三种可能的情况。尚未添加正确的注释 - @ Controller,@ Repository或@Controller ;尚未添加组件扫描;组件包中未定义所需要的组件包名。

有两个解决选项:1)添加注释或组件扫描2)将组件移动到已在组件扫描下的包中

@Component和@ComponentScan有什么区别?

@Component和@ComponentScan用于不同目的。

  • @Component表示一个类可能是创建bean的候选者。就像举手一样。
  • @ComponentScan正在搜索组件包。试图找出谁都举起手来。

推荐一个Java架构群909723834,群里有学习资料和面试资料获取,里面都是同行,相互帮助相互学习(资料找群主即可免费获取)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值