詳解Spring系列之@ComponentScan批量注冊bean
回顧
在前面的章節(jié),我們介紹了@Comfiguration和@Bean結(jié)合AnnotationConfigApplicationContext零xml配置文件使用Spring容器的方式,也介紹了通過<context:component-scan base-package="org.example"/>掃描包路徑下的bean的方式。如果忘了可以看下前面幾篇。這篇我們來結(jié)合這2種方式來理解@ComponentScan
本文內(nèi)容
@ComponentScan基本原理和使用
@ComponentScan進(jìn)階使用
@Componet及其衍生注解使用
@ComponentScan基本原理和使用
基本原理
源碼中解析為配置組件掃描指令與@Configuration類一起使用提供與 Spring XML 的 <context:component-scan> 元素同樣的作用支持。簡單點(diǎn)說,就是可以掃描特定包下的bean定義信息,將其注冊到容器中,并自動提供依賴注入。
@ComponentScan可以對應(yīng)一下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。
默認(rèn)情況下,使用@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進(jìn)階使用
源碼簡析
@ComponentScan源碼和解析如下
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Repeatable(ComponentScans.class)
public @interface ComponentScan {
// 見 basePackages
@AliasFor("basePackages")
String[] value() default {};
// 指定掃描組件的包路徑,為空則默認(rèn)是掃描當(dāng)前類所在包及其子包
@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;
// 指示是否應(yīng)啟用使用 @Component @Repository @Service @Controller 注釋的類的自動檢測。
boolean useDefaultFilters() default true;
// 指定哪些類型適合組件掃描。進(jìn)一步將候選組件集從basePackages中的所有內(nèi)容縮小到與給定過濾器或多個(gè)過濾 器匹配的基本包中的所有內(nèi)容。
// <p>請注意,除了默認(rèn)過濾器(如果指定)之外,還將應(yīng)用這些過濾器。將包含指定基本包下與給定過濾器匹配的任 何類型,即使它與默認(rèn)過濾器不匹配
Filter[] includeFilters() default {};
// 定哪些類型不適合組件掃描
Filter[] excludeFilters() default {};
// 指定是否應(yīng)為延遲初始化注冊掃描的 bean
boolean lazyInit() default false;
}其中用到的Filter類型過濾器的源碼和解析如下
@Retention(RetentionPolicy.RUNTIME)
@Target({})
@interface Filter {
// 過濾的類型 支持注解、類、正則、自定義等
FilterType type() default FilterType.ANNOTATION;
@AliasFor("classes")
Class<?>[] value() default {};
// 指定匹配的類型,多個(gè)時(shí)是OR關(guān)系
@AliasFor("value")
Class<?>[] classes() default {};
// 用于過濾器的匹配模式,valua沒有配置時(shí)的替代方法,根據(jù)type變化
String[] pattern() default {};
}FilterType的支持類型如下
| 過濾類型 | 樣例表達(dá)式 | 描述 |
|---|---|---|
| annotation (default) | org.example.SomeAnnotation | 在目標(biāo)組件的類型級別存在的注釋。 |
| assignable | org.example.SomeClass | 目標(biāo)組件可分配(擴(kuò)展或?qū)崿F(xiàn))的類(或接口) |
| aspectj | org.example..*Service+ | 要由目標(biāo)組件匹配的 AspectJ 類型表達(dá)式。 |
| regex | org\.example\.Default.* | 與目標(biāo)組件的類名匹配的正則表達(dá)式。 |
| custom | org.example.MyTypeFilter | org.springframework.core.type.TypeFilter 接口的自定義實(shí)現(xiàn)。 |
案例1:使用Filters過濾
忽略所有@Repository 注釋并使用特定包下正則表達(dá)式來匹配*Repository
@Configuration
@ComponentScan(basePackages = "org.example",
includeFilters = @Filter(type = FilterType.REGEX, pattern = ".*My.*Repository"),
excludeFilters = @Filter(Repository.class))
public class AppConfig {
// ...
}案例2:使用自定義的bean名稱生成策略
自定義一個(gè)生成策略實(shí)現(xiàn)BeanNameGenerator 接口
/**
* 自定義的bean名稱生成策略
* @author zfd
* @version v1.0
* @date 2022/1/19 9:07
* @關(guān)于我 請關(guān)注公眾號 螃蟹的Java筆記 獲取更多技術(shù)系列
*/
public class MyNameGenerator implements BeanNameGenerator {
public MyNameGenerator() {
}
@Override
public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
// bean命名統(tǒng)一采用固定前綴+類名
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 可用于默認(rèn)為生成的 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 管理的組件一樣,自動檢測組件的默認(rèn)和最常見的范圍是單例??梢允褂?code>@Scope 注解中提供范圍的名稱,針對單個(gè)組件。
@Scope("prototype") //
@Repository
public class MovieFinderImpl implements MovieFinder {
// ...
}針對全部掃描組件,可以提供自定義作用域策略。
自定義策略實(shí)現(xiàn)ScopeMetadataResolver接口
/**
* 自定義作用域策略
* @author zfd
* @version v1.0
* @date 2022/1/19 9:32
* @關(guān)于我 請關(guān)注公眾號 螃蟹的Java筆記 獲取更多技術(shù)系列
*/
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 管理的組件的通用原型注解。在使用基于注釋的配置和類路徑掃描時(shí),此類類被視為自動檢測的候選對象
@Repository、@Service 和 @Controller 是 @Component 針對更具體的用例(分別在持久層、服務(wù)層和表示層)的特化。
簡單看一下的注解@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 提供的許多注解都可以在您自己的代碼中用作元注解。元注釋是可以應(yīng)用于另一個(gè)注釋的注釋。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component // @Component 導(dǎo)致 @Service 以與 @Component 相同的方式處理
public @interface Service {
// ...
}可以組合元注釋來創(chuàng)建“組合注釋”,例如@RestController就是@ResponseBody和@Controller的組合。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
@AliasFor(annotation = Controller.class)
String value() default "";
}組合注釋可以選擇從元注釋中重新聲明屬性以允許自定義。這在只想公開元注釋屬性的子集時(shí)可能特別有用。
例如,Spring 的 @SessionScope 注解將作用域名稱硬編碼為 session,但仍允許自定義 proxyMode。
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Scope(WebApplicationContext.SCOPE_SESSION)
public @interface SessionScope {
// 重新聲明了元注解的屬性并賦予了默認(rèn)值
@AliasFor(annotation = Scope.class)
ScopedProxyMode proxyMode() default ScopedProxyMode.TARGET_CLASS;
}Spring 中對java的注解增強(qiáng)之一: 通過@AliasFor聲明注解屬性的別名,此機(jī)制實(shí)現(xiàn)了通過當(dāng)前注解內(nèi)的屬性給元注解屬性賦值。
總結(jié)
本文介紹各種@ComponentScan批量掃描注冊bean的基本使用以及進(jìn)階用法和@Componet及其衍生注解使用。
本篇源碼地址: https://github.com/kongxubihai/pdf-spring-series/tree/main/spring-series-ioc/src/main/java/com/crab/spring/ioc/demo08
知識分享,轉(zhuǎn)載請注明出處。學(xué)無先后,達(dá)者為先!
到此這篇關(guān)于詳解Spring系列之@ComponentScan批量注冊bean的文章就介紹到這了,更多相關(guān)Spring @ComponentScan批量注冊bean內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot構(gòu)建RESTful API的實(shí)現(xiàn)示例
本文主要介紹了SpringBoot構(gòu)建RESTful API的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05
Spring框架開發(fā)scope作用域分析總結(jié)
這篇文章主要介紹了Spring框架開發(fā)中scope作用域的分析總結(jié),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2021-09-09
用java開發(fā)dota英雄最華麗的技能(實(shí)例講解)
下面小編就為大家分享一篇使用java開發(fā)dota英雄最華麗的技能實(shí)例,具有非常好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-11-11
一個(gè)依賴搞定?Spring?Boot?接口防盜刷的流程分析
kk-anti-reptile 是適用于基于 spring-boot 開發(fā)的分布式系統(tǒng)的反爬蟲組件,這篇文章主要介紹了一個(gè)依賴搞定?Spring?Boot?接口防盜刷,需要的朋友可以參考下2022-06-06
java httpclient設(shè)置超時(shí)時(shí)間和代理的方法
這篇文章主要介紹了java httpclient設(shè)置超時(shí)時(shí)間和代理的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02

