开发者

Spring Dependency Injection

开发者 https://www.devze.com 2023-01-16 21:20 出处:网络
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 spr

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?


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.


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


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

精彩评论

暂无评论...
验证码 换一张
取 消