通过春天初始化我的工厂

时间:2012-08-13 14:10:16

标签: java spring initialization factory

我可以拥有如下工厂吗?

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;
    }

}
  1. 如何通过弹簧来处理工厂的初始化?
  2. 这种建造工厂的方式是否正确?
  3. 还有其他更好的方法吗?

2 个答案:

答案 0 :(得分:2)

  1. 不要将所有内容都设置为静态,尤其不是init()方法。
  2. 使用@Component
  3. 注释您的bean
  4. 使用init()
  5. 为您的@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配置中定义的映射。