Rakesh Goyal
Rakesh Goyal

Reputation: 3231

Spring Dependency Injection

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?

Upvotes: 0

Views: 531

Answers (3)

Tamiliniyan Devarajan
Tamiliniyan Devarajan

Reputation: 86

As long as your application is spring specific application, below simple steps might help to inject PhysicalDAO to PhysicalService in annotation way.

//Add this spring annotation to add your DAO class to Spring container
@Component("physicalDAO")
public class PhysicalDAO {

}

//Add Service class with PhysicalDAO object reference to use.
public class PhysicalService {

  @Autowired
  PhysicalDAO physicalDAO;

}

Define below entries to you spring configuration file.

<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.cognizant.aop.annotation"></context:component-scan>

Upvotes: 0

Adi Sembiring
Adi Sembiring

Reputation: 5946

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

Upvotes: 0

meriton
meriton

Reputation: 70584

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.

Upvotes: 1

Related Questions