我可以拥有如下工厂吗?
public class Factory
{
private static Map<EnumXyz, IDAO> map = new HashMap<Sting, Object>();
public static void init()
{
//how do i initialize my map through spring initialization
}
public static IDAO getDAO(EnumXyz dao)
{
if (map.containsKey(dao))
return map.get(dao);
else
{
throw new IllegalArgumentException("dao not supported " + dao);
}
return null;
}
}
答案 0 :(得分:2)
@Component
init()
。@PostConstruct
方法添加注释
醇>
现在,当Spring构造你的Factory类时调用init()
方法,为它提供一个初始化自己的钩子。
答案 1 :(得分:0)
我会将你的工厂实例化为bean本身,并且有一个实例 - 不要让所有东西都是静态的。 Spring本身可以控制你的bean是否是一个单例(它将默认为这样)。
e.g。
public class Factory {
public Factory(final Map<String,Object} map) {
this.map = map;
}
}
和你的Spring配置:
<bean id="myFactory" class="Factory">
<constructor-arg>
<util:map>
<!-- configure your map here, or reference it as a separate bean -->
<entry key="java.lang.String" value="key">....</entry>
</util:map>
</constructor-arg>
</bean>
在构造函数中,传入Spring配置中定义的映射。