Spring Boot的Component Scan原理

  本问将帮助您了解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错误,让你很恼火哦。

#######详细示例

考虑下面:

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正在搜索组件包。试图找出谁都举起手来。

 

Spring Boot