tags:

views:

68

answers:

2

Hi All, I am quite new to Spring DI. We have two classes, PhysicalService and PhysicalDAO. Physical service instance is being created dynamically using some service handler, hence it is not spring managed bean. Physical DAO instance is managed by Spring Beans. Is there any way by which I can inject physical dao in physical service?

+1  A: 

Is the service handler a spring bean? Then you can inject the DAO into the service handler, and the service handler can provide it to the service when it creates it.

Alternatively, you can use lookup injection to inject a prototype service bean into the handler, effectively providing a factory method in the handler that asks spring to instantiate the service.

That said, I wonder why you need a service handler? Are you sure you can't use spring to create the services?

Edit: If you can get rid of the property file I'd turn all services into spring beans whose ids match the id provided to the handler, inject the application context into the service handler, and do:

public Object getInstance(String id) {
    return applicationContext.getBean(id);
}

To migrate the property file spring bean definitions, I'd use regular expression replacement.

meriton
I am tryig to refactor the existing code. Service Handler is using factory pattern and service instance is being created based on some id. We have getInstance(String id) method, based on the id, we are getting class name from a property file and creating the instance for the same.
A: 

You said ServiceHandler that crate PhysicalService using Factory Pattern.

First you must inject PhysicalDAO to the factory, you can define it in spring context or using autowired annotation.

//spring-context.xml
<bean id="physicalDAO" class="package.dao.PhysicalDAO">
//inject reference needed by dao class
</bean>

<bean id="physicalServiceFactory" class="package.service.PhysicalServiceFactory">
        <property name="physicalDAO" ref="physicalDAO " ></property>
</bean>

and in your factory class you can write code as follows:

PhysicalServiceFactory {
    private PhysicalDAO physicalDAO;

    public void setPhysicalDAO(PhysicalDAO _physicalDAO) {
        physicalDAO = _physicalDAO;
    }

    public PhysicalService create(String id) {
        PhysicalService ps = PhysicalService(id);
        ps.setPhysicalDAO(physicalDAO);
            return ps;
    }
}
adisembiring