2015-01-15 82 views
0

我們有一些遺留代碼,我試圖找出一種清理方法。我想到的一種解決方案是,我可以根據給定的枚舉值注入自定義處理程序。我可以基於枚舉來限定注入嗎?我想這樣的東西也許(僞代碼)我可以根據Enum限定注射嗎?

@Service(MyEnum.MYVALUE, MyEnum.MYOTHERVALUE) // produces a handler given these enums 
public class MyHandler { ... } 

@Service(MyEnum.ANOTHERVALUE) 
public class AnotherHandler {... } 

// .... some mystical way of telling spring what my current enum context is so I can get the right handler 

回答

0

我不認爲這會奏效。

首先,@ServicevalueString,而不是Enum[]。而且,它只是建議爲該服務類註冊的bean的名稱。

相反,我認爲你可能想要使用的是@Qualifier。所以,你可以有類似:

@Service 
@Qualifier("foo") 
public class FooHandler implements IHandler { ... } 

@Service 
@Qualifier("bar") 
public class BarHandler implements IHandler { ... } 

@Component 
public class MyThing { 
    @Autowired @Qualifier("foo") 
    private IHandler handler; 

    ... 
} 

或者,您可以創建自己的自定義限定註解,如:

@Retention(RetentionPolicy.RUNTIME) 
@Target({ElementType.FIELD, ElementType.TYPE, ElementType.PARAMETER}) 
@Qualifier 
public @interface MyQualifier { ... } 

@Service 
@MyQualifier 
public class FooHandler implements IHandler { ... } 

@Component 
public class MyClass { 
    @Autowired @MyQualifier 
    private IHandler handler; 

    ... 
} 

詳情請參閱Fine-tuning annotation-based autowiring with qualifiers

+0

並不是真的暗示'@ Service'參數是一個枚舉,這就是爲什麼我說「僞代碼」,我不確定我要找的代碼是什麼 – xenoterracide 2015-01-16 02:42:48

0

那麼,你可以嘗試創建你自己的驗證(是的,即使有枚舉),然後提供你自己的BeanPostProcessor,它將完成這項工作並將值注入到帶註釋的字段中。

有很多Spring BeanPostProcessor,所以你可以通過瀏覽Spring的源代碼來看看它是如何完成的。

相關問題