我有一个看起来像这样的类:
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 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"
,或者这无关紧要?我是否正确设置了静态属性?还有什么我需要做或考虑的吗?提前致谢。