本文内容
-
@ComponentScan
基本原理和使用 -
@ComponentScan
进阶使用 -
@Componet
及其衍生注解使用
@ComponentScan基本原理和使用
基本原理
源码中解析为配置组件扫描指令与@Configuration
类一起使用提供与 Spring XML 的 <context:component-scan>
元素同样的作用支持。简单点说,就是可以扫描特定包下的bean定义信息,将其注册到容器中,并自动提供依赖注入。
@ComponentScan
可以对应一下xml配置。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.example"/>
</beans>
提示: 使用
<context:component-scan>
隐式启用<context:annotation-config>
的功能,也就是扫描批量注册并自动DI。
默认情况下,使用@Component
、@Repository
、@Service
、@Controller
、@Configuration
注释的类或本身使用@Component 注释的自定义注释是会作为组件被@ComponentScan
指定批量扫描到容器中自动注册。
使用案例
定义组件
@Component
public class RepositoryA implements RepositoryBase {
}
@Component
public class Service1 {
@Autowired
private RepositoryBase repository;
}
定义配置类
@Configuration
@ComponentScan(basePackages = "com.crab.spring.ioc.demo08")
public class AppConfig {
}
容器扫描和使用
@org.junit.Test
public void test_component_scan1() {
AnnotationConfigApplicationContext context =
new Annot