2011-09-08 114 views
2

在J6SE中是否有任何其他方式获取spring(spring 3.0)应用程序上下文而不是实现ApplicationContextAware接口?Spring应用程序上下文

对不起,我必须改进我的问题。我在我的J6SE应用程序中运行应用程序上下文,并在某些类中需要它。

回答

2

在阅读完您的问题后,我知道您正在寻找ApplicationContextAware的替代方案,但我读到您有许多使用ApplicationContext的类的目标,但希望避免为所有这些类实现接口。此方法仍使用ApplicationContextAware,但将其封装到单个类中以供重用。

我通常通过web.xml中的ContextLoaderListener在应用程序启动时加载配置。发生这种情况后,我将“MyApplicationContext”设置为contextApplicationContextProvider。

<bean id="contextApplicationContextProvider" class="pkg.MyApplicationContext"></bean> 

这个类必须实现了ApplicationContextAware因为你已经建议:

public class MyApplicationContext implements ApplicationContextAware { 

    private static ApplicationContext appContext; 

    /* (non-Javadoc) 
    * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext) 
    */ 
    @Override 
    public void setApplicationContext(ApplicationContext globalAppContext) 
     throws BeansException { 

     this.appContext = globalAppContext; 

    } 

    public static ApplicationContext getApplicationContext() { 
     return appContext; 
    } 

} 

的这里关键是,你现在有一个静态参考的ApplicationContext对象的单个实例。检索它很简单,通过使用静态方法调用MyApplicationContext.getApplicationContext()为任何类,弹簧管理或不。

+0

是的,我有这种实现像单身人士。但我有想法提供枚举类型的daos,我需要设置应用程序。在这个枚举中的上下文。我不喜欢在这个枚举中使用我的单例的方式。 –

+0

如果我理解正确,你会想要一个枚举注入DAO。鉴于枚举本质上是静态的,我不相信Spring IoC可以管理这些bean并因此注入任何东西。从静态Singleton访问应用程序上下文视图是我意识到实现此目标的唯一方式。 – jbabuscio

0

您可以从CLASSPATH中加载它。

0
new FileSystemXmlApplicationContext(APPLICATION_CONTEXT_FILE); 
0
@Inject 
private ApplicationContext ctx; 

(或者@Autowired代替@Inject)。这是ApplicationContextAware的注释替换。这当然意味着物体需要成为春天的豆子。

相关问题