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

查看:58
本文介绍了获取 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,只需实现BeanFactoryAwareApplicationContextAware 接口.

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天全站免登陆