我有一个看起来像这样的类(class):
public class Configurator {
private static Configurator INSTANCE = null;
private int maxRange = 1;
// many other properties; each property has a default value
private static synchronized Configurator getInstance() {
if(INSTANCE == null)
return new Configurator();
return INSTANCE;
}
public static int getMaxRange() {
getInstance().maxRange;
}
public static void setMaxRange(int range) {
getInstance().maxRange = range;
}
// Getters and setters for all properties follow this pattern
}
它作为一个全局配置对象,可以在应用启动时设置,然后被整个项目的几十个类使用:
// Called at app startup to configure everything
public class AppRunner {
Configurator.setMaxRange(30);
}
// Example of Configurator being used by another class
public class WidgetFactory {
public void doSomething() {
if(Configurator.getMaxRange() < 50)
// do A
else
// do B
}
}
我现在将此代码导入 Spring 项目,并尝试配置我的 Sprinig XML (bean)。我的猜测是我可以像这样(或类似的东西)定义一个单独的 Configurator
bean:
<bean id="configurator" class="com.me.myapp.Configurator" scope="singleton">
<property name="maxRange" value="30"/>
<!-- etc., for all properties -->
</bean>
这样,当 WidgetFactory#doSomething
执行时,Spring 就已经加载了 Configurator
类并提前配置好了。
我设置 scope="singleton"
是否正确,或者这无关紧要?我是否正确设置了静态属性?还有什么我需要做或考虑的吗?提前致谢。
最佳答案
作为一种设计模式的单例与 Spring 的单例工具之间存在一些差异。单例作为一种设计模式将确保您为每个类加载器定义一个类对象。相比之下,Spring 的单例工具(和方法)将为每个 Spring Context 定义一个实例。
在这种情况下,您可以利用 Spring 使用的 getInstance()
方法来获取您的对象实例:
<bean id="configurator" class="com.me.myapp.Configurator" factory-method="getInstance">
</bean>
对于 Spring,singleton
bean 范围是默认的,因此您不需要定义它。
如果你想使用 configurator
作为 Spring bean,你必须将它注入(inject)到其他对象中,而不是使用 getInstance()
来获取它。所以在其他 Spring bean 中使用 @Autowired 或通过 xml 文件定义对 bean 的引用。如果你不重新组织 configurator
在其他类中的使用,没有区别,Spring 会实例化你的类,但你会像以前一样使用它。
我还看到您在设计单例时存在错误。您的 getInstance()
方法应该是公共(public)的,其他方法不应该是静态的。在您使用的示例中,您应该像这样使用 Singleton:
Configurator.getInstance().someMethod()
在这种情况下,您实际上只是使用 Singleton 类,而不实例化任何对象!见 wikipedia on Singleton (with Java example)有关单例设计模式及其使用方法的更多信息。
注意:值得了解并尝试将
Configurator
用作单例并使用 Spring 的单例功能。如果你这样做,好处将是你可以
- 去掉
getInstance()
方法 - 公开你的构造函数
- 让 Spring 实例化该单个对象。
关于java - Spring注入(inject)静态(全局)单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14645047/