user978939
user978939

Reputation: 131

initializing my factory through spring

Can I have a factory as follows?

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. How do I take care of the initialization of my factory through spring?
  2. Is this way of building a factory correct?
  3. Any other, better approach?

Upvotes: 0

Views: 1681

Answers (2)

Brian Agnew
Brian Agnew

Reputation: 272297

I would instantiate your factory as a bean itself, and have an instance of it - don't make everything static. Spring itself can control whether your bean is a singleton (it will default as such).

e.g.

public class Factory {
   public Factory(final Map<String,Object} map) {
      this.map = map;
   }
}

and your Spring config:

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

In your constructor, pass in the map which is defined itself in your Spring config.

Upvotes: 0

Hiery Nomus
Hiery Nomus

Reputation: 17769

  1. Don't make everything static, especially not the init() method.
  2. Annotate your bean with @Component
  3. Annotate your init() method with @PostConstruct.

Now the init() method is called when Spring constructs your Factory class, providing it a hook to initialize itself.

Upvotes: 2

Related Questions