1.10,Classpath Scanning and Managed Components
本章中的大多數示例使用XML配置,
上一節(基于注解的容器配置)演示了如何通過注解配置bean,雖說是注解配置,但基本”bean”定義也顯式地定義在XML檔案中,而注解僅驅動依賴項注入,
本節描述通過掃描classpath隱式檢測候選Spring組件, 候選組件是指滿足篩選標準的類,并有相應的bean definition 注冊到容器中,
這樣就不需要使用XML來執行bean注冊,
相反,您可以使用注解(例如@Component)、AspectJ型別運算式或您自己的自定義篩選標準來選擇哪些類已經向容器注冊了bean定義,
從Spring 3.0開始,Spring JavaConfig專案提供的許多特性都是核心Spring框架的一部分,
這允許您使用Java而不是傳統的XML檔案定義bean,
比如:@Configuration、@Bean、@Import和@DependsOn
1.10.1,@Component和構造型注解
@Repository注解是滿足存盤庫角色或構造型的任何類的標記(也稱為資料訪問物件或DAO),
該標記的使用還可以進行例外的自動翻譯,能將所標注的類中拋出的資料訪問例外封裝為Spring的資料訪問例外型別,
Spring提供了進一步的構造型注解:@Component, @Service和@Controller,
@Component是任何spring管理組件的通用原型,
@Repository、@Service和@Controller則是針對更具體用例(分別在持久性、服務和表示層中),它們是@Component的細化,
因此,您可以使用@Component來注解組件類,但是,通過使用@Repository、@Service或@Controller來注解它們,您的類更適合通過工具進行處理或與方面關聯,
例如,這些構造型注解是AOP切點的理想目標,
@Repository、@Service和@Controller還可以在Spring框架的未來版本中附帶額外的語意,就像@Repository的例外翻譯一樣,
因此,如果您要在您的服務層使用@Component或@Service之間進行選擇,那么@Service顯然是更好的選擇,
類似地,如前所述,@Repository已經被支持作為持久化層中自動例外轉換的標記,
1.10.2,使用元注解和組合注解
Spring提供的許多注解都可以在您自己的代碼中用作元注解,
元注解是可以應用于另一個注解的注解,
例如,@Service注解上存在元注解@Component,如下面的示例所示:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
// ...
}
//@Component的存在導致Spring以@Component的方式來對待@Service,
您還可以結合使用元注解來創建“組合注解”,
例如,Spring MVC中的注解 @RestController 由@Controller和 組成@ResponseBody,
此外,組合注解可以選擇從元注解中重新宣告屬性,以允許自定義,
當您只希望公開元注解屬性的子集時,這特別有用,
例如,Spring的 @SessionScope注解將@Scope的value屬性硬編碼為session,但仍允許自定義@Scope的proxyMode,
以下清單顯示了SessionScope注解的定義 :
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Scope(WebApplicationContext.SCOPE_SESSION)
public @interface SessionScope {
/**
* Alias for {@link Scope#proxyMode}.
* <p>Defaults to {@link ScopedProxyMode#TARGET_CLASS}.
*/
@AliasFor(annotation = Scope.class)
ScopedProxyMode proxyMode() default ScopedProxyMode.TARGET_CLASS;
}
然后,您@SessionScope無需宣告proxyMode以下即可使用:
@Service
@SessionScope
public class SessionScopedService {
// ...
}
您還可以覆寫的值proxyMode,如以下示例所示:
@Service
@SessionScope(proxyMode = ScopedProxyMode.INTERFACES)
public class SessionScopedUserService implements UserService {
// ...
}
1.10.3,自動檢測類并注冊Bean Definitions
Spring可以自動檢測構造型類,并使用來注冊相應的BeanDefinition實體ApplicationContext,
例如,以下兩個類別有資格進行這種自動檢測:
@Service
public class SimpleMovieLister {
private MovieFinder movieFinder;
public SimpleMovieLister(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
}
@Repository
public class JpaMovieFinder implements MovieFinder {
// implementation elided for clarity
}
要自動檢測這些類并注冊相應的bean,您需要添加@ComponentScan到@Configuration類中,
其中basePackages屬性是兩個類的公共父包,(或者,您可以指定一個逗號分隔,分號分隔或空格分隔的串列,其中包括每個類的父包,)
@Configuration
@ComponentScan(basePackages = "org.example")
public class AppConfig {
// ...
}
以下使用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>,
<context:annotation-config>使用時通常不需要包含 元素<context:component-scan>,
此外,當您使用component-scan元素時,AutowiredAnnotationBeanPostProcessor和 CommonAnnotationBeanPostProcessor都隱式包括在內,
這意味著將自動檢測這兩個組件并將它們連接在一起,而這一切都不需要XML中提供的任何bean配置元資料,
您可以通過包括annotation-config與屬性的值false禁用注冊AutowiredAnnotationBeanPostProcessor并 CommonAnnotationBeanPostProcessor,
如下所示:
<context:component-scan base-package="org.springframework.example" annotation-config="false"/>
1.10.4,使用過濾器自定義掃描
默認情況下,僅檢測到用@Component、@Repository、@Service、@Controller、@Configuration注釋的類或本身用@Component注釋的自定義注釋,
但是,您可以通過應用自定義過濾器來修改和擴展此行為,
比如修改@ComponentScan注解的includeFilters或excludeFilters屬性(或context:component-scan元素中context:include-filter或context:exclude-filter子元素),
下表描述了篩選選項:
表5.過濾器型別
| 過濾器型別 | 舉例 | 描述 |
|---|---|---|
| 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介面的自定義實作, |
@Configuration
@ComponentScan(basePackages = "org.example",
includeFilters = @Filter(type = FilterType.REGEX, pattern = ".*Stub.*Repository"),
excludeFilters = @Filter(Repository.class))
public class AppConfig {
...
}
以下清單顯示了等效的XML:
<beans>
<context:component-scan base-package="org.example">
<context:include-filter type="regex"
expression=".*Stub.*Repository"/>
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
</beans>
您也可以通過設定useDefaultFilters=false注解
或通過修改<component-scan/>元素的use-default-filters="false"的屬性來禁用默認過濾器,
這樣有效地禁止的注解或元注解的類自動檢測(@Component,@Repository,@Service,@Controller, @RestController,或@Configuration),
1.10.5,在組件中定義Bean元資料
Spring組件也可以向容器提供bean定義元資料,
您可以使用與在@Configuration注解類中定義bean元資料相同的@Bean注解來做到這一點,
下面的例子展示了如何做到這一點:
@Component
public class FactoryMethodComponent {
@Bean
@Qualifier("public")
public TestBean publicInstance() {
return new TestBean("publicInstance");
}
public void doWork() {
// Component method implementation omitted
}
}
前面的類是一個Spring組件,在它的doWork()方法中有特定于應用程式的代碼,
但是,它也提供了一個bean定義,其中有一個參考方法publicInstance()的工廠方法,
@Bean注解標識工廠方法和其他bean定義屬性,例如通過@Qualifier注解標識的限定符值,其他可以用的方法級注解還包括@Scope、@Lazy和自定義Qualifier注釋,
@Lazy除了用于組件初始化的角色外,
您還可以將@Lazy注解放置在標有@Autowired或的注入點上@Inject,
在這種情況下,它導致注入了惰性決議代理,
如前所述,支持自動注入的欄位和方法,并自動支持@Bean方法的附加支持,
以下示例顯示了如何執行此操作:
@Component
public class FactoryMethodComponent {
private static int i;
@Bean
@Qualifier("public")
public TestBean publicInstance() {
return new TestBean("publicInstance");
}
//privateInstance.age 的值會被自動注入
//Qualifier值為public的bean會被注入
@Bean
protected TestBean protectedInstance(
@Qualifier("public") TestBean spouse,
@Value("#{privateInstance.age}") String country) {
TestBean tb = new TestBean("protectedInstance", 1);
tb.setSpouse(spouse);
tb.setCountry(country);
return tb;
}
@Bean
private TestBean privateInstance() {
return new TestBean("privateInstance", i++);
}
@Bean
@RequestScope
public TestBean requestScopedInstance() {
return new TestBean("requestScopedInstance", 3);
}
}
在Spring Framework 4.3中,您還可以宣告一個型別為InjectionPoint的工廠方法引數(或者它更具體的子類:DependencyDescriptor)來訪問觸發當前bean創建的請求注入,能看到當前bean是作為哪個bean的屬性被實體化的(比如:實體化時的屬性名,實體化所處的類等),
注意,這只適用于bean實體的實際創建時候,現有實體被注入的時候不會觸發,
因此,這個特性對prototype 范圍的bean最有意義,
對于其他范圍,工廠方法只能看到在給定范圍內觸發新bean實體創建的注入點(例如,觸發惰性單例bean創建的依賴項),
您可以在這樣的場景中謹慎使用提供的注入點元資料,
下面的例子展示了如何使用InjectionPoint:
@Component
public class FactoryMethodComponent {
@Bean
@Scope("prototype")
public TestBean prototypeInstance(InjectionPoint injectionPoint) {
return new TestBean("prototypeInstance for " + injectionPoint.getMember());
}
}
常規Spring組件中的@Bean方法與Spring @Configuration類中的對應方法處理方式不同,
區別在于@Configuration類會被CGLIB增強過,@Component類沒有通過CGLIB增強來攔截方法和欄位的呼叫,
您可以將@Bean方法宣告為靜態的,允許在不將包含它的配置類創建為實體的情況下呼叫它們,
這在定義后處理器bean(例如,BeanFactoryPostProcessor或BeanPostProcessor型別)時特別有意義,
因為這樣的bean在容器生命周期的早期被初始化,應該避免在此時觸發配置的其他部分,
容器永遠不會攔截對靜態@Bean方法的呼叫,甚至在@Configuration類中也不會(如本節前面所述),由于技術限制:CGLIB子類化只能覆寫非靜態方法,
Java語言中@Bean方法的可見性對Spring容器中生成的bean定義沒有直接影響,
您可以自由地在non-@Configuration類中宣告您的工廠方法,也可以在任何地方宣告靜態方法,
但是,@Configuration類中的常規@Bean方法需要被重寫——也就是說,它們不能被宣告為private或final,
@Bean方法也可以在給定組件或配置類的基類中發現,
也可以在Java 8中在組件或配置類實作的介面中宣告的默認方法中發現,
這為組合復雜配置安排提供了很大的靈活性,甚至多重繼承在java8的默認方法下也成為了可能,
interface OneClass{
default void printOne(){
System.out.println("print one");
}
}
interface TwoClass{
default void printTwo(){
System.out.println("print two");
}
}
public class SonClass implements OneClass, TwoClass {
public static void main(String[] args) {
SonClass son = new SonClass();
son.printOne();
son.printTwo();
}
}
每個介面都定義了一個默認方法,因此SonClass類可以從這兩個介面呼叫方法,這就像多重繼承,
最后,一個類可能為同一個bean保留多個@Bean方法,作為多個工廠方法的安排,在運行時根據可用的依賴項使用,
這與在其他配置場景中選擇建構式或工廠方法是相同的演算法:在構建時選擇可滿足依賴關系最多的變數,類似于容器在多個@Autowired構造函式之間進行選擇,
如下:
@Bean
public ServiceTwo serviceTwo(InjectionPoint injectionPoint){
return new ServiceTwo();
}
@Bean
public ServiceTwo serviceTwo(InjectionPoint injectionPoint, CusService cusService){
return new ServiceTwo();
}
這兩個bean只會實體化一個來使用
1.10.6,命名自動檢測的組件
當一個組件作為掃描程序的一部分被自動檢測時,
它的bean名稱是由掃描器知道的BeanNameGenerator策略生成的,
默認情況下,一些Spring注解(@Component, @Repository, @Service,和@Controller)包含一個名為value的屬性,可以提供名稱給相應的bean定義,
如果value值不包含任何名稱值,那么默認的bean名稱生成器將回傳類名稱首字母小寫的字串作為beanName,
例如,如果檢測到以下組件類,名稱將是myMovieLister和movieFinderImpl:
@Service("myMovieLister")
public class SimpleMovieLister {
// ...
}
@Repository
public class MovieFinderImpl implements MovieFinder {
// ...
}
如果不想依賴默認的Bean命名策略,則可以提供自定義Bean命名策略,
首先,實作 BeanNameGenerator介面,并確保包括默認的no-arg建構式,
然后,在配置掃描程式時提供完全限定的類名,如以下示例注解和Bean定義所示,
@Configuration
@ComponentScan(basePackages = "org.example", nameGenerator = MyNameGenerator.class)
public class AppConfig {
// ...
}
或者
<beans>
<context:component-scan base-package="org.example"
name-generator="org.example.MyNameGenerator" />
</beans>
如果由于自動檢測到的多個組件具有相同的非限定類名(即具有相同名稱但位于不同包中的類)而遇到命名沖突,
您可能需要配置一個以類的全路徑作為beanName的BeanNameGenerator,
在Spring Framework 5.2.3中,位于package org.springframework.context中的FullyQualifiedAnnotationBeanNameGenerator 可用于此,
public class FullyQualifiedAnnotationBeanNameGenerator extends AnnotationBeanNameGenerator {
@Override
protected String buildDefaultBeanName(BeanDefinition definition) {
String beanClassName = definition.getBeanClassName();
Assert.state(beanClassName != null, "No bean class name set");
return beanClassName;
}
}
作為一般規則,當其他組件可能顯式地參考該注解時,請考慮使用該注釋指定名稱,
另一方面,只要容器負責連接,自動生成的名稱就足夠了,
1.10.7,提供自動檢測組件的范圍
一般而言,與Spring管理的組件一樣,自動檢測到的組件的默認范圍也是最常見的范圍是singleton,
但是,有時您需要@Scope注解可以指定的其他范圍,
您可以在批注中提供范圍的名稱,如以下示例所示:
@Scope("prototype")
@Repository
public class MovieFinderImpl implements MovieFinder {
// ...
}
@Scope注解僅在具體的bean類(對于任何的@Component注解)或工廠方法(對于@Bean方法)上進行使用,
與XML bean定義相反,沒有bean定義繼承的概念,并且在類級別的繼承層次結構與元資料目的無關,
有關特定于web的作用域的詳細資訊,看本系列的第五篇文章,
要為Scope決議提供自定義策略,而不是依賴于基于注解的方法,您可以實作ScopeMetadataResolver介面,確保包含默認的無引數建構式,
然后,在配置掃描器時,您可以提供完全限定的類名,如下面的注釋和bean定義示例所示:
@Configuration
@ComponentScan(basePackages = "org.example", scopeResolver = MyScopeResolver.class)
public class AppConfig {
// ...
}
或者
<beans>
<context:component-scan base-package="org.example" scope-resolver="org.example.MyScopeResolver"/>
</beans>
在使用某些非單例作用域時,可能需要為作用域物件生成代理,
其原因還是因為作用域的問題,比如作用域為單例bean的參考prototype的bean,則需要使用代理,否則單例bean將始終持有prototype的一個實體,
為此,component-scan元素上有一個作用域代理屬性,三個可能的值是:no、interface和targetClass,
例如,以下配置導致了標準JDK動態代理:
@Configuration
@ComponentScan(basePackages = "org.example", scopedProxy = ScopedProxyMode.INTERFACES)
public class AppConfig {
// ...
}
或者
<beans>
<context:component-scan base-package="org.example" scoped-proxy="interfaces"/>
</beans>
1.10.8,生成候選組件的索引
雖然類路徑掃描非常快,但是可以通過在編譯時創建一個靜態候選串列來提高大型應用程式的啟動性能,
其實就是把所有需要注冊成bean的類在編譯時就篩選出來了,啟動時直接用,不需要全部遍歷了,
在這種模式下,所有作為組件掃描目標的模塊都必須使用這種機制,
您現有的@ComponentScan或當ApplicationContext檢測到這樣一個索引時,
它會自動使用它,而不是掃描類路徑,
要生成索引,請向包含組件掃描指令目標組件的每個模塊添加額外的依賴項,
下面的例子展示了如何使用Maven來實作這一點:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-indexer</artifactId>
<version>5.2.9.RELEASE</version>
<optional>true</optional>
</dependency>
</dependencies>
對于Gradle 4.5和更早版本,應在compileOnly 配置中宣告依賴項,如以下示例所示:
dependencies {
compileOnly "org.springframework:spring-context-indexer:5.2.9.RELEASE"
}
對于Gradle 4.6和更高版本,應在annotationProcessor 配置中宣告依賴項,如以下示例所示:
dependencies {
annotationProcessor "org.springframework:spring-context-indexer:{spring-version}"
}
該程序將生成一個META-INF/spring.components的檔案包含在jar檔案中,
內容如下:
org.springframework.example.Cancel=org.springframework.stereotype.Component
org.springframework.example.Transfer=org.springframework.stereotype.Component
在IDE中使用此模式時,spring-context-indexer必須將其注冊為注解處理器,以確保在更新候選組件時索引是最新的,
當在類路徑中找到META-INF/spring.components時,索引會自動啟用,
如果索引對于某些庫(或用例)是部分可用的,但不能為整個應用程式構建,那么您可以通過設定spring.index.ignore為true回傳到常規的類路徑安排,
本文由博客一文多發平臺 OpenWrite 發布!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/174415.html
標籤:其他
下一篇:Activiti~相關概念
