最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解Spring系列之@ComponentScan批量注冊bean

 更新時間:2022年02月15日 08:49:36   作者:kongxubihai  
本文介紹各種@ComponentScan批量掃描注冊bean的基本使用以及進(jìn)階用法和@Componet及其衍生注解使用,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧

回顧

在前面的章節(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> 元素同樣的作用支持。簡單點說,就是可以掃描特定包下的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)容縮小到與給定過濾器或多個過濾			器匹配的基本包中的所有內(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 {};
		// 指定匹配的類型,多個時是OR關(guān)系
		@AliasFor("value")
		Class<?>[] classes() default {};
		// 用于過濾器的匹配模式,valua沒有配置時的替代方法,根據(jù)type變化
		String[] pattern() default {};
	}

FilterType的支持類型如下

過濾類型樣例表達(dá)式描述
annotation (default)org.example.SomeAnnotation在目標(biāo)組件的類型級別存在的注釋。
assignableorg.example.SomeClass目標(biāo)組件可分配(擴展或?qū)崿F(xiàn))的類(或接口)
aspectjorg.example..*Service+要由目標(biāo)組件匹配的 AspectJ 類型表達(dá)式。
regexorg\.example\.Default.*與目標(biāo)組件的類名匹配的正則表達(dá)式。
customorg.example.MyTypeFilterorg.springframework.core.type.TypeFilter 接口的自定義實現(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名稱生成策略

自定義一個生成策略實現(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 注解中提供范圍的名稱,針對單個組件。

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

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

自定義策略實現(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 管理的組件的通用原型注解。在使用基于注釋的配置和類路徑掃描時,此類類被視為自動檢測的候選對象

@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)用于另一個注釋的注釋。

@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 "";
}

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

例如,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的注解增強之一: 通過@AliasFor聲明注解屬性的別名,此機制實現(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)文章

  • Java快速排序QuickSort(實例)

    Java快速排序QuickSort(實例)

    下面小編就為大家?guī)硪黄狫ava快速排序QuickSort(實例)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-10-10
  • Java實現(xiàn)圖形界面計算器

    Java實現(xiàn)圖形界面計算器

    這篇文章主要為大家詳細(xì)介紹了Java實現(xiàn)圖形界面計算器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • SpringSecurity使用PasswordEncoder加密用戶密碼的示例代碼

    SpringSecurity使用PasswordEncoder加密用戶密碼的示例代碼

    PasswordEncoder是Spring Security庫中的一個關(guān)鍵組件,它主要用于處理密碼的安全存儲和驗證,本文將給大家介紹一下SpringSecurity使用PasswordEncoder加密用戶密碼的方法,需要的朋友可以參考下
    2024-09-09
  • 使用@ApiModel遇到的問題及解決

    使用@ApiModel遇到的問題及解決

    這篇文章主要介紹了使用@ApiModel遇到的問題及解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-06-06
  • mysql高版本(8.0+)group_by報錯的處理方法

    mysql高版本(8.0+)group_by報錯的處理方法

    本文主要介紹了mysql高版本(8.0+)group_by報錯的處理方法,這個錯誤一般發(fā)生在mysql 5.7以及 5.7以上的版本中,本文就來介紹一下兩種解決方法,感興趣的可以了解一下
    2023-09-09
  • feign客戶端設(shè)置超時時間操作

    feign客戶端設(shè)置超時時間操作

    這篇文章主要介紹了feign客戶端設(shè)置超時時間操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-09-09
  • Mybatis 如何批量刪除數(shù)據(jù)的實現(xiàn)示例

    Mybatis 如何批量刪除數(shù)據(jù)的實現(xiàn)示例

    這篇文章主要介紹了Mybatis 如何批量刪除數(shù)據(jù)的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03
  • Servlet+JDBC實現(xiàn)登陸功能的小例子(帶驗證碼)

    Servlet+JDBC實現(xiàn)登陸功能的小例子(帶驗證碼)

    這篇文章主要介紹了Servlet+JDBC實現(xiàn)登陸功能的小例子(帶驗證碼),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-06-06
  • SpringBoot接口數(shù)據(jù)加解密實戰(zhàn)記錄

    SpringBoot接口數(shù)據(jù)加解密實戰(zhàn)記錄

    現(xiàn)今對于大多數(shù)公司來說,信息安全工作尤為重要,下面這篇文章主要給大家介紹了關(guān)于SpringBoot接口數(shù)據(jù)加解密的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-07-07
  • MyBatis Plus更新對象無法設(shè)空值解決方案

    MyBatis Plus更新對象無法設(shè)空值解決方案

    這篇文章主要介紹了MyBatis Plus更新對象無法設(shè)空值解決方案,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-11-11

最新評論

攀枝花市| 信丰县| 平阳县| 佳木斯市| 伽师县| 甘洛县| 黄龙县| 钦州市| 同德县| 宁夏| 乐亭县| 万全县| 清河县| 台东市| 河源市| 巨鹿县| 巩义市| 布尔津县| 吐鲁番市| 富宁县| 耿马| 延津县| 古浪县| 松阳县| 鸡西市| 利川市| 平江县| 玛沁县| 新河县| 天津市| 扎赉特旗| 怀远县| 桂阳县| 临朐县| 新沂市| 东安县| 东宁县| 青浦区| 长治市| 石泉县| 隆昌县|