在不使用Singleton的情况下从非bean对象获取Spring Application上下文 [英] Getting Spring Application context from a non bean object without using Singleton

查看:66
本文介绍了在不使用Singleton的情况下从非bean对象获取Spring Application上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从非bean对象获取spring应用程序上下文.在SO的另一个线程中,可接受的答案建议使用单例来获取应用程序上下文.获取Spring应用程序上下文

I need to get the spring application context from a non bean object. In another thread in SO, the accepted answer suggests to use singleton to get the application context. Getting Spring Application Context

但是,使用单例使我的代码更易于耦合和测试,这是许多线程中讨论的常见问题(例如

But using singleton makes my code more coupled and less testable, the usual problems discussed in many threads (e.g. What is so bad about Singletons )

问题是,有没有一种优雅的方法可以在不使用单例的情况下从非bean对象获取应用程序上下文?

The question, is there an elegant way to get the application context from a non bean object without using singleton?

推荐答案

总是存在引导问题.对于Web应用程序,通常是使用外部servlet过滤器来处理这种情况.

There's always the bootstrapping problem. For web applications there's usually the outer servlet filter that handles the situation.

如果不是Web应用程序,则无法绕过某种外部单例或引导程序.但;在这里使用单例应该只影响该单个引导程序类的可测试性.在您的代码中,实际上应该只有很少的地方需要以任何显式的方式引用容器.因此,它并没有真正显着增加耦合.

If not a web-app, there's no way around some kind of outer singleton or bootstrapper. But; using a singleton here should only affect the testability of that single bootstrapper class. There should really only be very few places in your code that need to reference the container in any explicit manner. So it does not really increase coupling significantly.

或者换句话说,实际上应该只有很少的非bean对象需要访问spring容器.如果不是这种情况,则可能不是最佳使用spring.并且大多数/所有需要该容器的容器可能应该只实现 ApplicationContextAware

Or to rephrase, there should really only be very few non-bean objects that need to access the spring container. If this is not the case, then you're probably not using spring optimally. And most/all of those that need the container should probably just implement BeanFactoryAware or ApplicationContextAware

这篇关于在不使用Singleton的情况下从非bean对象获取Spring Application上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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