簡體   English   中英

使用Spring連接未在列表中實現標記接口的bean

[英]Wiring beans that do not implement an tag interface in list using Spring

我有一組擴展抽象類Executor類。 假設這些類是ExecutorOneExecutorTwoExecutorThree 然后,我有第四個類擴展Executor類型, ExecutorFour ,還實現了NotUsable接口。

我使用Spring 4.x將所有上述bean的實例注入到列表中。

@Autowired
private final List<Executor> executors;

是否有任何機制允許我不在列表executors注入ExecutorFour類型的bean? 我希望列表executors只包含三個bean,分別是ExecutorOneExecutorTwoExecutorThree類型。

我試着看看@Conditional注釋,但似乎在這種情況下沒用。

提前致謝。

還有另一種選擇,它有助於實現您的嘗試,但不會直接回答問題。

Spring沒有像這樣的排除機制,畢竟,所有4個bean都是有效的spring bean並且已經創建。

但是,您可以Usable NotUsable接口,而不是NotUsable標記接口。 這是一個(幾乎不言自明)的例子:

interface Executor {}

interface UsableExecutor extends Executor {}

class Executor1 implements UsableExecutor{...}
class Executor2 implements UsableExecutor{...}
class Executor3 implements UsableExecutor{...}
class Executor4 implements Executor {}  // note, doesn't implement UsableExecutor

@Component
class SomeClassWithUsableExecutors {

   private final List<UsableExecutor> usableExecutors;

   // an autowired constructor - only 3 elements will be in the list 
   public SomeClassWithUsableExecutors(List<UsableExecutor> usableExecutors) {
      this.usableExecutors = usableExecutors;
   } 
}

雖然Spring沒有為@Autowired提供“排除這些類”語法,但它以@Qualifier的形式提供了“包含這些類”的支持。

這種方法的工作方式是創建一個自定義限定符,您將在類級別應用於您希望在運行時成為@AutowiredExecutor類。 Spring完成剩下的工作以確保不需要的類不會進入列表:

  1. 創建自定義限定符,以應用於所需的類:

     @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Qualifier public @interface Usable { String value(); } 
  2. 在注射點應用您的限定符:

     @Autowired @Usable private final List<Executor> executors; 

上面的內容現在只有具有自定義@Usable限定符的Executor類才會被注入executors

暫無
暫無

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

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