Nital
Nital

Reputation: 6084

How to initialize or configure a singleton/factory method in spring?

I have following factory method which I would like to initialize in spring XML.

public final class ProductDaoFactory {

    private static final ProductDaoFactory INSTANCE = new ProductDaoFactory();

    //so cannot new an intance
    private ProductDaoFactory() {
    }

    //singleton
    public static ProductDaoFactory getInstance() {
        return INSTANCE;
    }

    //factory method
    public ProductDao getProductDao(String daoType) {
        ProductDao productDao = null;

        if ("jdbc".equalsIgnoreCase(daoType)) {
            productDao = new ProductDaoJdbcImpl();
        } else if ("ibatis".equalsIgnoreCase(daoType)) {
            productDao = new ProductDaoIBatisImpl();
        } else if ("hibernate".equalsIgnoreCase(daoType)) {
            productDao = new ProductDaoHibernateImpl();
        }

        return productDao;
    }
}

Is the following correct way to configure it?

<bean id="productDaoFactory" class="com.ministore.dao.factory.ProductDaoFactory" factory-method="getInstance"></bean>  
<bean id="productDaoFactory" class="com.ministore.dao.factory.ProductDaoFactory" factory-method="getProductDao">
    <property name="daoType" value="jdbc" />
</bean>  

Upvotes: 0

Views: 1911

Answers (1)

You can try the following bean configurations.

<bean id="productDaoFactory" class="com.ministore.dao.factory.ProductDaoFactory" factory-method="getInstance"/>

    <bean id="jdbcProductDao" factory-bean="productDaoFactory" factory-method="getProductDao">
        <constructor-arg value="jdbc"/>
    </bean>

    <bean id="hibernateProductDao" factory-bean="productDaoFactory" factory-method="getProductDao">
        <constructor-arg value="hibernate"/>
    </bean>

    <bean id="iBatisProductDao" factory-bean="productDaoFactory" factory-method="getProductDao">
        <constructor-arg value="ibatis"/>
    </bean>

Upvotes: 1

Related Questions