回顧
在前面的章節,我們介紹了@Comfiguration和@Bean結合AnnotationConfigApplicationContext零xml組態檔使用Spring容器的方式,也介紹了通過<context:component-scan base-package="org.example"/>掃描包路徑下的bean的方式,如果忘了可以看下前面幾篇,這篇我們來結合這2種方式來理解@ComponentScan
本文內容
-
@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 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 = https://www.cnblogs.com/kongbubihai/archive/2022/02/14/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及其衍生注解使用,
本篇原始碼地址: https://github.com/kongxubihai/pdf-spring-series/tree/main/spring-series-ioc/src/main/java/com/crab/spring/ioc/demo08
知識分享,轉載請注明出處,學無先后,達者為先!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/423814.html
標籤:其他
上一篇:二叉樹的基本操作(C語言版)
