2013-09-25 27 views
4

我有一個包含相同的組件的兩個自動裝配Autowired實例豆:如何使用註釋在@Scope(「prototype」)bean中指定特定於實例的@Value?

@Component 
public SomeBean { 
    @Autowired 
    private SomeOtherBean someOtherBean1; 
    @Autowired 
    private SomeOtherBean someOtherBean2; 
    ... 
} 

SomeOtherBean具有原型範圍:

@Component 
@Scope("prototype") 
public SomeOtherBean { 
    @Value("...") 
    private String configurable; 
} 

的可配置值需要是不同的用於每個自動裝配SomeOtherBean和將通過屬性佔位符提供:

configurable.1=foo 
configurable.2=bar 

理想情況下,我想使用註釋來指定值e可配置屬性。

通過XML這樣做會很容易,但我想知道這是否是

  • 一)不可能註釋或
  • b)如何可以做到的。
+0

您是否嘗試過'@ Qualifier'? – chrylis

+1

你的意思是限定@Autowired依賴?這仍然沒有定義如何在SomeOtherBean實例中指定兩個特定的值。 –

+0

你有沒有找到解決這個問題的方法?我問了一個類似的問題,但沒有得到任何支持。這很容易用xml和setter來完成,但似乎沒有將它變成基於註釋的配置。 – thedarklord47

回答

1

也許這是略有不同的你在想什麼,但你可以做到這一點很容易與@Configuration爲基礎的方法,例如:

@Configuration 
public class Config { 

    @Bean 
    @Scope("prototype") 
    public SomeOtherBean someOtherBean1(@Value("${configurable.1}") String value) { 
     SomeOtherBean bean = new SomeOtherBean(); 
     bean.setConfigurable(value); 
     return bean; 
    } 

    @Bean 
    @Scope("prototype") 
    public SomeOtherBean someOtherBean2(@Value("${configurable.2}") String value) { 
     // etc... 
    } 
} 
+0

喬納森的好主意,該解決方案按照需要工作。然而,它確實混淆了我的代碼,它使用了Spring專用的代碼,完全沒有商業用途 - 與Spring註釋應該是相反的:-) –

+0

爲什麼這會混淆你的代碼?這基本上只是配置,否則你會把它放在xml中。 –

+0

正如我所說,喬納森提出的解決方案按照需要工作,但它不回答我的問題。我仍然想知道是否有某種機制允許'@Scope(「prototype」)'定義'@ Component's用不同的'@ Value'自動配置。這可能是不可能的。 –

相關問題