簡體   English   中英

Spring 排除過濾器

[英]Spring exclude filter

內部應用程序上下文.xml:

<context:component-scan base-package="com.myApp">
        <context:exclude-filter type="assignable" expression="com.myApp.MyService"/>
</context:component-scan>

<bean id="myService" class="com.myApp.ExtendedService" />

在 Main.java 內部:

@SpringBootApplication
@ImportResource(locations = {"classpath:application-context.xml"})
public class Main{
    //...
}

內部擴展服務:

@Service
public class ExtendedService extends MyService{
    //...
}

但是當我開始時,我得到 Invalid Bean definition because myService is bound 錯誤。 如何排除原來的MyService?

例外:

由以下原因引起:org.springframework.beans.factory.support.BeanDefinitionOverrideException:在 URL [文件:svc.xml] 中定義的名稱為“myService”的無效 bean 定義:無法注冊 bean 定義 [通用 bean:class [com.myApp.ExtendedService] ; 范圍=; 摘要=假; 懶惰初始化=假; 自動接線模式=1; 依賴檢查=0; autowireCandidate=真; 初級=假; 工廠BeanName=null; 工廠方法名=空; 初始化方法名=空; destroyMethodName=null; 在 URL [file:svc.xml]] 中為 bean 'myService' 定義:已經有 [Generic bean: class [com.myApp.MyService]; 范圍=單例; 摘要=假; 懶惰初始化=假; 自動接線模式=0; 依賴檢查=0; autowireCandidate=真; 初級=假; 工廠BeanName=null; 工廠方法名=空; 初始化方法名=空; destroyMethodName=null; 定義在 URL [jar:file:/.m2/repository/com/myApp/myLib-1.0.0.jar./com/myApp/MyService.class]] 綁定。

@SpringBootApplication 正在對相同(和子)包進行 package 掃描。 這相當於@Configuration @EnableAutoConfiguration @ComponentScan。 如果您不想進行 package 掃描,可以替換為其他 2 個。

@Configuration
@EnableAutoConfiguration
@ImportResource(locations = {"classpath:application-context.xml"})
public class Main{
    //...
}

編輯:您可以在 ExtendedService 上使用 @Primary,上下文將使用這個而不是 MyService,那么您不需要在掃描中排除。 這僅在 MyService 不是主要服務時才有效。

@Primary
@Service
public class ExtendedService extends MyService{
    //...
}

EDIT2:您不能使用 assignable 排除,因為這兩個服務都可以分配給 MyService 使用正則表達式。

<context:exclude-filter type="regex" expression="com.myApp.MyService"/>

您實際上不必使用 XML 配置,它們仍然受支持,但看起來確實過時了。

基本上,您可以采用兩種不同的路徑:

解決方案 1

只有在滿足某些條件(通過屬性表示,類路徑中存在 class,甚至自定義邏輯)時,才使用@Conditional加載ExtendedService的 bean

@Service
@ConditionalOnProperty(name = "feature.x.enabled", havingValue = "true")
public class ExtendedService extends MyService {
}

這將導致只有在按如下方式提供屬性時才會加載 bean(在 application.properties / yaml 或 spring 引導識別的任何其他方式):

feature.x.enabled=true

到目前為止,這是我可以推薦的最干凈的解決方案

方案二

另一種解決方案基於定制受組件掃描影響的路徑的能力。 默認情況下與 package 相同,其中主要的 class(帶有@SpringBootApplication注釋的那個所在)及其在任何級別的所有子包。

因此,如果您想從組件掃描過程中排除此 class,您可以執行以下操作:

@SpringBootApplication
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,
        classes = ExtendedService .class))
public class Main {
    public static void main(...) {...}
}

請注意,您可能需要閱讀本教程以獲取更多信息的多種過濾器類型

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM