【发布时间】:2013-02-06 05:14:27
【问题描述】:
假设我有以下结构,其中有一个服务接口 ServiceInterface 和几个实现它的组件:ProductAService 和 ProductBService 我还有一个 RequestContext bean,它有一个限定属性,表明我们是说当前正在处理 ProductA 或 ProductB。然后如何通过自动装配或其他注释将正确的实现(ProductAService 或 ProductBService)自动注入到需要它的某些服务中(下面的ServiceThatNeedsServiceInterface)。
public interface ServiceInterface {
void someMethod();
}
@Component(name="ProductAService")
public class ProductAService implements ServiceInterface {
@Override public void someMethod() {
System.out.println("Hello, A Service");
}
}
@Component(name="ProductBService")
public class ProductBService implements ServiceInterface {
@Override public void someMethod() {
System.out.println("Hello, B Service");
}
}
@Component
public class ServiceThatNeedsServiceInterface {
// What to do here???
@Autowired
ServiceInterface service;
public void useService() {
service.someMethod();
}
}
@Component
@Scope( value = WebApplicationContext.SCOPE_REQUEST )
public class RequestContext {
String getSomeQualifierProperty();
}
【问题讨论】:
标签: java spring dependency-injection annotations