从域对象中访问Spring单例的好方法? [英] Good way to access Spring singleton from within domain objects?
问题描述
我有一个域模型,它由相当大的对象图组成,其中域对象正在创建其他域对象,依此类推。为了各种目的,每个域对象都需要访问少量单例类型的辅助对象。
I have a domain model that consists of fairly large object graphs, where domain objects are creating other domain objects and so forth. Each of these domain objects needs access to a small handful of singleton-type helper objects for various purposes.
当我记得我已经在使用Spring时,我正准备使用Java单例模式实现它们,我可以使用Spring在应用程序中实例化这些助手中的每一个启动。
I was about to implement them using the Java singleton pattern when I remembered that I am already using Spring and I can use Spring to instantiate one of each of these helpers at application startup.
我的问题是如何从我的域对象中找到它们?这些都是通过new运算符创建的对象,不受Spring控制。
My question is how to I find them from within my domain objects? These are all objects that are created via the "new" operator and are not under the control of Spring.
我想我可以使用getBean方法我掌握了Spring应用程序上下文(我没有) - 但是这个好的表现是什么?我需要这些东西快速...以及如何快速获取应用程序上下文?
I'm thinking I could use the "getBean" method if I had my hands on the Spring application context (which I don't) -- but is the performance of this good? I need this stuff to be fast... And how to quickly get the application context?
推荐答案
public class SpringApplicationContextProvider implements ApplicationContextAware {
public void setApplicationContext(ApplicationContext ctx)
throws BeansException {
// Wiring the ApplicationContext into a static method
SpringApplicationContext.setApplicationContext(ctx);
}
}
并将SpringApplicationContext定义为,
And define SpringApplicationContext as,
public class SpringApplicationContext {
private static ApplicationContext ctx;
public static void setApplicationContext(
ApplicationContext applicationContext) {
ctx = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return ctx;
}
private SpringApplicationContext(){
}
}
在配置文件中将SpringApplicationContextProvider定义为spring bean。现在可以使用此提供程序访问应用程序上下文。
Define SpringApplicationContextProvider as a spring bean in your config file. Now the application context can be accessed using this provider.
这篇关于从域对象中访问Spring单例的好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!