2016-09-30 66 views
1

這裏需要一些幫助。 在我們的項目中,我們使用XML和註釋配置(春季4.1) 最近,我遇到了以下任務:在春季將原型列表注入Singleton bean中

我的範圍原型豆名單,他們都實現了相同的接口。

另外我有一個singleton bean有execute方法。在該方法內部,bean應該訪問這些原型bean的列表。

每次執行'execute'方法時,我都想要訪問這些原型bean的不同實例)。 在單例中,我沒有提前知道bean的全部列表,所以我只需@Autowire整個集合,以便應用程序上下文中已知的每個bean實現都將被加載。

interface SomeInterface { 

} 


class PrototypeBean1 implements SomeInterface { 
    ... 
} 

class PrototypeBean2 implements SomeInterface { 
    ... 
} 


class MySingletonBean { 

    @Autowire (????) 
    List<SomeInterface> allPrototypeBeansLoadedIntoTheApplicationContext; 

    public void execute() { 
     // this one is called many times, 
     // so I would like to get different lists of  
     //"allPrototypeBeansLoadedIntoTheApplicationContext" 
     // with different actuals bean upon every invocation 
     // how do I achieve this??? 
    } 

} 

所以我的問題是:什麼是最乾淨的方式來實現這一目標?理想情況下,我想得到一個完全從彈簧接口解耦的解決方案(如注入ApplicationContext/BeanFactory的東西) 我不介意在這裏使用Aop(性能不是那麼重要),但我無法真正包裹我的頭一個乾淨的春天解答。所以任何幫助將不勝感激。

在此先感謝

回答

1

我一直在努力實現與Spring類似的目標和閱讀使用任何ServiceLocatorFactoryBeanmethod injection(與 @Lookup)過來了,看着有希望的春天文檔後。 然而,經過嘗試兩種方法的結果竟然令人沮喪。在列表中都不支持返回的bean。而我得到這個異常:

類型沒有合格豆「java.util.List的」可用

顯然春季處理的返回類型爲普通對象。

因此,最終我的解決方案成爲創建一個新的對象來包裝列表作爲返回類型。

@Component 
@Scope("prototype") 
public class ProcessorList 
{ 
    private List<Processor> processors; 

    public ProcessorList(List<Processor> processors) 
    { 
     this.processors = processors; 
    } 

    public List<Processor> getProcessors() 
    { 
     return processors; 
    } 

    public void setProcessors(List<ChangeSetProcessor> processors) 
    { 
     this.processors = processors; 
    } 
} 

然後創建一個工廠類的列表對象:

@Component 
public interface ProcessorFactory 
{ 
    ProcessorList getProcessorList(); 
} 

然後使用ServiceLocatorFactoryBean註冊工廠:

@Configuration 
public class MyConfiguration{ 
    @Bean 
    public FactoryBean serviceLocatorFactoryBean() 
    { 
     ServiceLocatorFactoryBean factoryBean = new ServiceLocatorFactoryBean(); 
     factoryBean.setServiceLocatorInterface(ProcessorFactory.class); 
     return factoryBean; 
    } 

} 

最後實現接口,並確保它們標記所有@Scope(「原型」)

現在你會得到新的實例,每次喲你使用工廠方法!

如果您願意,它與使用方法注射相似。