2011-03-29 71 views
4

我想在傳統應用程序中使用Spring。Spring:將啓動ApplicationContext的對象注入ApplicationContext

核心部分是一類,我們稱之爲LegacyPlugin,它表示應用程序中的一種可插入部分。問題是,這個類也是數據庫連接器,以及用於創建許多其他的對象,通常是通過構造函數注入...

我想從LegacyPlugin推出一個ApplicationContext,並注入例如,ApplicationContext通過BeanFactory創建其他對象。代碼將被重寫,使用setter注入&等等。

我想知道什麼是實現這一目標的最佳方法。到目前爲止,我有一個使用BeanFactory的工作版本,它使用ThreadLocal來保存對當前執行的插件的靜態引用,但對我來說似乎很難...

下面是我想結束的代碼:

public class MyPlugin extends LegacyPlugin { 

    public void execute() { 
     ApplicationContext ctx = new ClassPathXmlApplicationContext(); 
     // Do something here with this, but what ? 
     ctx.setConfigLocation("context.xml"); 
     ctx.refresh(); 
    } 

} 

<!-- This should return the object that launched the context --> 
<bean id="plugin" class="my.package.LegacyPluginFactoryBean" /> 

<bean id="someBean" class="my.package.SomeClass"> 
    <constructor-arg><ref bean="plugin"/></constructor-arg> 
</bean> 

<bean id="someOtherBean" class="my.package.SomeOtherClass"> 
    <constructor-arg><ref bean="plugin"/></constructor-arg> 
</bean> 
+0

如果你有訪問類你想要注入應用程序上下文?我不確定我是否理解每個課程背後的理論基礎? – Fil 2011-03-29 20:35:49

+0

基本上,我想擺脫插件內部的大量初始化代碼。 – mexique1 2011-03-30 09:13:33

回答

0

其實,這也不行......這將導致以下錯誤:

BeanFactory not initialized or already closed 
call 'refresh' before accessing beans via the ApplicationContext 

最終的解決方案是使用GenericApplicationContext

GenericApplicationContext ctx = new GenericApplicationContext(); 
ctx.getBeanFactory().registerSingleton("plugin", this); 
new XmlBeanDefinitionReader(ctx).loadBeanDefinitions(
    new ClassPathResource("context.xml")); 
ctx.refresh(); 
4

SingletonBeanRegistry界面允許用戶通過其registerSingleton方法手動注入預先配置的單進入的上下文中,這樣的:

ApplicationContext ctx = new ClassPathXmlApplicationContext(); 
ctx.setConfigLocation("context.xml"); 

SingletonBeanRegistry beanRegistry = ctx.getBeanFactory(); 
beanRegistry.registerSingleton("plugin", this); 

ctx.refresh(); 

這會將plugin bean添加到上下文中。您不需要在context.xml文件中聲明它。

+0

嗯,有用的,我不知道BeanRegistry ...但我寧願明確地在春天的上下文文件。 – mexique1 2011-03-30 09:12:07

+0

@ mexique1:爲什麼?它有什麼不同? – skaffman 2011-03-30 09:20:20

+0

嗯...抱歉,遲到的接受。畢竟,我在幾個項目上使用了@ Service/@ Component註釋,這或多或少是一樣的:你不知道如何,但是bean在那裏。感謝您的答覆。 – mexique1 2011-04-01 15:01:35

相關問題