美文网首页
Spring Boot的Component Scan原理你了解了

Spring Boot的Component Scan原理你了解了

作者: 猿生进阶 | 来源:发表于2020-12-26 22:00 被阅读0次

本文将帮助您了解Spring中最重要的概念 - 组件扫描。Spring Boot在组件扫描方面做了一些魔术
@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错误,让你很恼火哦。

详细示例

考虑下面:

<pre style="box-sizing: border-box; 
font-family: inherit; font-size: 1em; 
margin: 1em 0px; padding: 12px 10px; 
white-space: pre-wrap; border: 1px solid rgb(232, 232, 232);
 position: relative; line-height: 1.5; 
color: rgb(153, 153, 153); 
background: rgb(244, 245, 246);">package com.jdon.springboot
@SpringBootApplication
public class MyApplication {
 public static void main(String[] args) {
 SpringApplication.run(MyApplication.class, args);
 }
}
</pre>

@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”})

与组件扫描相关的错误

<pre style="box-sizing: border-box;
 font-family: inherit; font-size: 1em; 
margin: 1em 0px; padding: 12px 10px;
 white-space: pre-wrap; border: 1px solid rgb(232, 232, 232);
 position: relative; line-height: 1.5;
 color: rgb(153, 153, 153); 
background: rgb(244, 245, 246);"> 
#### No qualifying bean of type found 
</pre>

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发现。

你需要检查三种可能的情况。

  1. 尚未添加正确的注释 - @ Controller,@ Repository或@Controller ;
  2. 尚未添加组件扫描;
  3. 组件包中未定义所需要的组件包名。

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

@Component和@ComponentScan有什么区别?

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

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

相关文章

网友评论

      本文标题:Spring Boot的Component Scan原理你了解了

      本文链接:https://www.haomeiwen.com/subject/iphnnktx.html