【发布时间】:2017-08-12 01:35:51
【问题描述】:
在给定运行时值的情况下,我找不到注入组件/服务的简单方法。
我开始阅读@Spring的文档:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-autowired-annotation-qualifiers 但我找不到如何改变传递给 @Qualifier 注释的值。
假设我有一个具有这种接口的模型实体:
public interface Case {
String getCountryCode();
void setCountryCode(String countryCode);
}
在我的客户端代码中,我会执行以下操作:
@Inject
DoService does;
(...)
Case myCase = new CaseImpl(); // ...or whatever
myCase.setCountryCode("uk");
does.whateverWith(myCase);
...我的服务是:
@Service
public class DoService {
@Inject
// FIXME what kind of #$@& symbol can I use here?
// Seems like SpEL is sadly invalid here :(
@Qualifier("${caze.countryCode}")
private CaseService caseService;
public void whateverWith(Case caze) {
caseService.modify(caze);
}
}
我希望 caseService 是 UKCaseService(请参阅下面的相关代码)。
public interface CaseService {
void modify(Case caze);
}
@Service
@Qualifier("uk")
public class UKCaseService implements CaseService {
}
@Service
@Qualifier("us")
public class USCaseService implements CaseService {
}
那么我如何以最简单/优雅/有效的方式通过使用任何一个/所有 Spring 特性来“修复”所有这些,所以基本上没有 .properties,没有 XML,只有注释。 但是我已经怀疑我的 DoService 有问题,因为 Spring 在注入 caseService 之前需要知道“案例”......但是如何在客户端代码不知道 caseService 的情况下实现这一点?! 我想不通...
我已经在这里阅读了几个关于 SO 的问题,但大多数时候,要么他们的需求和/或配置与我不同,要么发布的答案对我来说不够满意(看起来他们'本质上是变通办法或(旧)使用(旧)Spring特性)。
How does Spring autowire by name when more than one matching bean is found? => 仅指类组件类
Dynamically defining which bean to autowire in Spring (using qualifiers) => 真的很有趣,但最详尽的答案(4 票)是......几乎 3 1/2 岁?! (2013 年 7 月)
Spring 3 - Dynamic Autowiring at runtime based on another object attribute =>这里的问题非常相似,但答案看起来真的是一种解决方法而不是真正的设计模式(如工厂)?而且我不喜欢将所有代码都实现到 ServiceImpl 中...
Spring @Autowiring, how to use an object factory to choose implementation? => 第二个答案似乎很有趣,但它的作者没有扩展,所以虽然我(有点)了解 Java Config 和东西,但我不太确定他在说什么......
How to inject different services at runtime based on a property with Spring without XML => 有趣的讨论,尤其是。答案,但用户设置了我没有的属性。
另请阅读: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html#expressions-bean-references => 我找不到关于在表达式中使用“@”的扩展示例。有人知道吗?
编辑: 发现了其他相关的类似问题,没有人得到正确的答案: How to use @Autowired to dynamically inject implementation like a factory pattern Spring Qualifier and property placeholder Spring: Using @Qualifier with Property Placeholder How to do conditional auto-wiring in Spring? Dynamic injection in Spring SpEL in @Qualifier refer to same bean How to use SpEL to inject result of method call in Spring?
工厂模式可能是一个解决方案? How to use @Autowired to dynamically inject implementation like a factory pattern
【问题讨论】:
标签: spring service dependency-injection autowired