问题描述
我正在将单例转换为Spring bean,因此如果单例无法初始化,则整个Web应用程序的spring上下文无法正确加载。
I am converting a singleton to a Spring bean, so that if the singleton fails to initialize, then entire web application's spring context doesn't load properly.
使Spring上下文无法正确加载的好处是人们会在部署过程中注意并修复配置。与使用'非spring bean'单例相反:当在初始化期间抛出异常时,没有人注意到..直到实际用户抱怨缺少功能。
The advantage of making the Spring context not load properly, is that people will take notice and fix the configuration during deployment itself. As opposed to using 'non-spring bean' singleton: when that throws exception during initialization, nobody notices.. until a actual user complains of missing functionality.
我的更改是按预期工作..但我不确定我做的是否正确。
有什么想法吗?
My changes are working as expected.. but I am not sure if I am doing the right thing.
Any thoughts?
代码如下:
public class MySingleton {
private static MySingleton INSTANCE = null;
private MySingleton(){}
public static MySingleton getInstance(){
if(INSTANCE == null){
synchronized(MySingleton.class){
if(INSTANCE == null){
try{
doWork()
}catch(Exception e){
throw new IllegalStateException("xyz", e);
}
INSTANCE = new MySingleton();
}
}
}
return INSTANCE;
}
private static void doWork() {
// do some work
}
}
在spring config xml中,bean将被定义为:
And in the spring config xml, the bean will be defined as:
<bean id="MySingletonBean"
class="com.MySingleton"
factory-method="getInstance" lazy-init="false" singleton="true">
</bean>
注意:
大部分内容类似于策略在本文中讨论:
编辑1:
使用这个单例的类不是spring bean本身..它们只是非弹簧pojos,我无法转换为spring。他们必须依靠getInstance()方法来获取Singleton。
The classes that use this singleton, are not spring beans themselves.. they are just non-spring pojos, that I can't convert to spring. They must rely on getInstance() method get hold of the Singleton.
编辑2: (将我在下面的评论复制到此说明部分)
我试图针对两件事:
Edit 2: (copying a comment I made below into this description section) I am trying to target two things:
- 我想要Spring初始化单身人士。因此,如果
初始化失败,则应用程序加载失败。 - 我希望其他类能够使用类而不必依赖contextAwareObj.getBean(MySingleton)
编辑3(最终):
我决定让这个班级成为单身人士......而且我不是把它变成一个春天的豆子。如果它无法初始化,它将在日志文件中记录一些内容..希望进行部署的人注意到....我放弃了我之前提到的方法,因为我觉得它将来会造成维护噩梦,所以我不得不选择 - 单身 - 或 - 春豆。我选择了单身。
EDIT 3 (FINAL):I decided to make this class a singleton.. and am not making it a spring bean. If it fails to initialize, it will log something in the Log file.. hopefully the person doing deployment takes notice.... I abandoned the approach I mentioned earlier because I feel it will create a maintenance nightmare in future, so I had to pick between - singleton - or - spring bean. I chose singleton.
推荐答案
你必须宣布 INSTANCE
字段为 volatile
,以便双重检查锁定才能正常工作。
You must declare the INSTANCE
field as volatile
for double-checked locking to work correctly.
参见,。
这篇关于使单例成为Spring bean的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!