Spring系列11:@ComponentScan批量註冊bean

回顧

在前面的章節,我們介紹了@Comfiguration@Bean結合AnnotationConfigApplicationContext零xml配置文件使用Spring容器的方式,也介紹了通過<context:component-scan base-package="org.example"/>掃描包路徑下的bean的方式。如果忘了可以看下前面幾篇。這篇我們來結合這2種方式來理解@ComponentScan

本文內容

  1. @ComponentScan基本原理和使用

  2. @ComponentScan進階使用

  3. @Componet及其衍生註解使用

@ComponentScan基本原理和使用

基本原理

源碼中解析為配置組件掃描指令與@Configuration類一起使用提供與 Spring XML 的 <context:component-scan> 元素同樣的作用支持。簡單點說,就是可以掃描特定包下的bean定義信息,將其註冊到容器中,並自動提供依賴注入。

@ComponentScan可以對應一下xml配置。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="//www.springframework.org/schema/beans"
    xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
    xmlns:context="//www.springframework.org/schema/context"
    xsi:schemaLocation="//www.springframework.org/schema/beans
        //www.springframework.org/schema/beans/spring-beans.xsd
        //www.springframework.org/schema/context
        //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 AnnotationConfigApplicationContext(AppConfig.class);
        Service1 service1 = context.getBean(Service1.class);
        System.out.println(service1);
        context.close();
    }

@ComponentScan進階使用

源碼簡析

@ComponentScan源碼和解析如下

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Repeatable(ComponentScans.class)
public @interface ComponentScan {

	// 見 basePackages
	@AliasFor("basePackages")
	String[] value() default {};

	// 指定掃描組件的包路徑,為空則默認是掃描當前類所在包及其子包
	@AliasFor("value")
	String[] basePackages() default {};

	// 指定要掃描帶注釋的組件的包 可替換basePackages
	Class<?>[] basePackageClasses() default {};

	// 用於命名 Spring 容器中檢測到的組件的類
	Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class;

	// 指定解析bean作用域的類
	Class<? extends ScopeMetadataResolver> scopeResolver() default AnnotationScopeMetadataResolver.class;

	// 指示為檢測到的組件生成代理的模式
	ScopedProxyMode scopedProxy() default ScopedProxyMode.DEFAULT;

	// 控制符合組件檢測條件的類文件;建議使用下面的 includeFilters excludeFilters
	String resourcePattern() default ClassPathScanningCandidateComponentProvider.DEFAULT_RESOURCE_PATTERN;

	// 指示是否應啟用使用 @Component @Repository @Service  @Controller 注釋的類的自動檢測。
	boolean useDefaultFilters() default true;

    // 指定哪些類型適合組件掃描。進一步將候選組件集從basePackages中的所有內容縮小到與給定過濾器或多個過濾			器匹配的基本包中的所有內容。
    // <p>請注意,除了默認過濾器(如果指定)之外,還將應用這些過濾器。將包含指定基本包下與給定過濾器匹配的任		何類型,即使它與默認過濾器不匹配
	Filter[] includeFilters() default {};

	//	定哪些類型不適合組件掃描
	Filter[] excludeFilters() default {};

	// 指定是否應為延遲初始化註冊掃描的 bean
	boolean lazyInit() default false;
}

其中用到的Filter類型過濾器的源碼和解析如下

@Retention(RetentionPolicy.RUNTIME)
	@Target({})
	@interface Filter {

		// 過濾的類型  支持註解、類、正則、自定義等
		FilterType type() default FilterType.ANNOTATION;

		@AliasFor("classes")
		Class<?>[] value() default {};

		// 指定匹配的類型,多個時是OR關係
		@AliasFor("value")
		Class<?>[] classes() default {};

		// 用於過濾器的匹配模式,valua沒有配置時的替代方法,根據type變化
		String[] pattern() default {};

	}

FilterType的支持類型如下

過濾類型 樣例表達式 描述
annotation (default) org.example.SomeAnnotation 在目標組件的類型級別存在的注釋。
assignable org.example.SomeClass 目標組件可分配(擴展或實現)的類(或接口)
aspectj org.example..*Service+ 要由目標組件匹配的 AspectJ 類型表達式。
regex org\.example\.Default.* 與目標組件的類名匹配的正則表達式。
custom org.example.MyTypeFilter org.springframework.core.type.TypeFilter 接口的自定義實現。

案例1:使用Filters過濾

忽略所有@Repository 注釋並使用特定包下正則表達式來匹配*Repository

@Configuration
@ComponentScan(basePackages = "org.example",
        includeFilters = @Filter(type = FilterType.REGEX, pattern = ".*My.*Repository"),
        excludeFilters = @Filter(Repository.class))
public class AppConfig {
    // ...
}

案例2:使用自定義的bean名稱生成策略

自定義一個生成策略實現BeanNameGenerator 接口

/**
 * 自定義的bean名稱生成策略
 * @author zfd
 * @version v1.0
 * @date 2022/1/19 9:07
 * @關於我 請關注公眾號 螃蟹的Java筆記 獲取更多技術系列
 */
public class MyNameGenerator implements BeanNameGenerator {
    public MyNameGenerator() {
    }

    @Override
    public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
        // bean命名統一採用固定前綴+類名
        return "crab$$" + definition.getBeanClassName();
    }
}

@ComponentScan中指定生成名稱策略

@Configuration
@ComponentScan(basePackages = "com.crab.spring.ioc.demo08",
nameGenerator = MyNameGenerator.class)
public class AppConfig {
}

從 Spring Framework 5.2.3 開始,位於包 org.springframework.context.annotation 中的 FullyQualifiedAnnotationBeanNameGenerator 可用於默認為生成的 bean 名稱的完全限定類名稱

測試輸出

@org.junit.Test
public void test_name_generator() {
    AnnotationConfigApplicationContext context =
            new AnnotationConfigApplicationContext(AppConfig.class);
    Service1 service1 = context.getBean(Service1.class);
    Arrays.stream(context.getBeanNamesForType(service1.getClass())).forEach(System.out::println);
    System.out.println(service1);
    context.close();
}
// bean名稱中存在我們自定義的命名了
crab$$com.crab.spring.ioc.demo08.Service1
com.crab.spring.ioc.demo08.Service1@769f71a9

案例3:自定義bean的作用域策略

與一般 Spring 管理的組件一樣,自動檢測組件的默認和最常見的範圍是單例。可以使用@Scope 註解中提供範圍的名稱,針對單個組件。

@Scope("prototype") // 
@Repository
public class MovieFinderImpl implements MovieFinder {
    // ...
}

針對全部掃描組件,可以提供自定義作用域策略。

自定義策略實現ScopeMetadataResolver接口

/**
 * 自定義作用域策略
 * @author zfd
 * @version v1.0
 * @date 2022/1/19 9:32
 * @關於我 請關注公眾號 螃蟹的Java筆記 獲取更多技術系列
 */
public class MyMetadataResolver implements ScopeMetadataResolver {
    @Override
    public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
        ScopeMetadata metadata = new ScopeMetadata();
        // 指定原型作用域
        metadata.setScopeName(BeanDefinition.SCOPE_PROTOTYPE);
        // 代理模式為接口
        metadata.setScopedProxyMode(ScopedProxyMode.INTERFACES);
        return metadata;
    }
}

@ComponentScan中指定作用域策略

@Configuration
@ComponentScan(basePackages = "com.crab.spring.ioc.demo08",
// nameGenerator = FullyQualifiedAnnotationBeanNameGenerator.class)
nameGenerator = MyNameGenerator.class,
scopeResolver = MyMetadataResolver.class
)
public class AppConfig {
}

@Componet及其衍生註解使用

@Component 是任何 Spring 管理的組件的通用原型註解。在使用基於注釋的配置和類路徑掃描時,此類類被視為自動檢測的候選對象

@Repository@Service@Controller @Component 針對更具體的用例(分別在持久層、服務層和表示層)的特化。

簡單看一下的註解@Component@Repository定義,其它的類似

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {

	// 指定組件名
	String value() default "";

}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component // 元註解@Component
public @interface Repository {
   @AliasFor(annotation = Component.class)
   String value() default "";

}

使用元註解和組合註解

Spring 提供的許多註解都可以在您自己的代碼中用作元註解。元注釋是可以應用於另一個注釋的注釋。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component // @Component 導致 @Service 以與 @Component 相同的方式處理
public @interface Service {

    // ...
}

可以組合元注釋來創建「組合注釋」,例如@RestController就是@ResponseBody@Controller的組合。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
	@AliasFor(annotation = Controller.class)
	String value() default "";

}

組合注釋可以選擇從元注釋中重新聲明屬性以允許自定義。這在只想公開元注釋屬性的子集時可能特別有用。

例如,Spring 的 @SessionScope 註解將作用域名稱硬編碼為 session,但仍允許自定義 proxyMode。

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Scope(WebApplicationContext.SCOPE_SESSION)
public @interface SessionScope {

    // 重新聲明了元註解的屬性並賦予了默認值
    @AliasFor(annotation = Scope.class)
    ScopedProxyMode proxyMode() default ScopedProxyMode.TARGET_CLASS;

}

Spring 中對java的註解增強之一: 通過@AliasFor聲明註解屬性的別名,此機制實現了通過當前註解內的屬性給元註解屬性賦值。

總結

本文介紹各種@ComponentScan批量掃描註冊bean的基本使用以及進階用法和@Componet及其衍生註解使用。

本篇源碼地址: //github.com/kongxubihai/pdf-spring-series/tree/main/spring-series-ioc/src/main/java/com/crab/spring/ioc/demo08
知識分享,轉載請註明出處。學無先後,達者為先!

Tags: