2013-10-28 23 views
6

在CDI,我可以這樣做:在Spring中是否有相當於CDI的@Default限定符?

// Qualifier annotation 
@Qualifier 
@inteface Specific{} 

interface A {} 

class DefaultImpl implements A {} 

@Specific 
class SpecificImpl implements A {} 

,然後在類:

@Inject 
A default; 

@Inject 
@Specific 
A specific; 

它的工作原理,因爲自動分配給不指定任何預選賽注射點@Default預選賽。

但我正在與Spring合作,無法執行該操作。

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException 

的問題是「默認」注射(不含資格賽)中大量的代碼,我不能改變已經習慣了,我需要爲我的用戶提供了另一種可能的實現的A

我知道我可以通過bean名稱注入我的新實現,但我想避免它。

春天有什麼能幫我實現嗎?

回答

11

有人指出@Primary完全是這樣做的。我試着和它完美的作品:

@Primary 
class DefaultImpl implements A {} 

在我的情況DefaultImpl是XML:

<bean id="defaultImpl" class="DefaultImpl" primary="true"/> 
0

我可以加入這個作爲一個評論,但我想與格式添加一些代碼來解釋我的點,這就是爲什麼我添加明確的答案。

添加到你所說的,實際上你可以在Spring中利用特定元註釋也,大意如下:

重新定義@Specific與Spring特定org.springframework.beans.factory.annotation.Qualifier註釋是這樣的:

import org.springframework.beans.factory.annotation.Qualifier; 
import org.springframework.context.annotation.Primary; 

import java.lang.annotation.ElementType; 
import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy; 
import java.lang.annotation.Target; 

@Qualifier 
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD}) 
@Retention(RetentionPolicy.RUNTIME) 
@Primary 
public @interface Specific { 
} 

我已經標記了具有@Primary註解的特定註釋。

有了這個地方你的舊代碼應該只是工作:

@Specific 
class DefaultImpl implements A {} 
+0

但在我的情況下,DefaultImpl不是'@ Specific'。它的SpecificImpl必須是'@ Specific'。 DefaultImpl必須是'Primary' – baraber

相關問題