获取Spring应用程序上下文 [英] Getting Spring Application Context

查看:142
本文介绍了获取Spring应用程序上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在Spring应用程序中静态/全局请求ApplicationContext的副本?

Is there a way to statically/globally request a copy of the ApplicationContext in a Spring application?

假设主类启动并初始化应用程序上下文,它需要通过调用堆栈向下传递给任何需要它的类,或者有没有办法让类要求先前创建的上下文? (我假设必须是一个单身?)

Assuming the main class starts up and initializes the application context, does it need to pass that down through the call stack to any classes that need it, or is there a way for a class to ask for the previously created context? (Which I assume has to be a singleton?)

推荐答案

如果需要访问容器的对象是一个bean容器,只需实现 BeanFactoryAware ApplicationContextAware 接口。

If the object that needs access to the container is a bean in the container, just implement the BeanFactoryAware or ApplicationContextAware interfaces.

如果容器外的对象需要访问容器,我使用了弹簧容器的标准GoF单例模式。这样,你的应用程序中只有一个单例,其余的都是容器中的单例bean。

If an object outside the container needs access to the container, I've used a standard GoF singleton pattern for the spring container. That way, you only have one singleton in your application, the rest are all singleton beans in the container.

这篇关于获取Spring应用程序上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆