我有三节课。
CurrencyUtil
需要NumberFormatter
。
NumberFormatter
仅被CurrencyUtilFactory
注入,因为CurrencyUtil
需要它。
有没有办法将NumberFormatter
直接注入CurrencyUtil
?
谢谢!
CurrencyUtil
public class CurrencyUtil {
private final LocalizationHelper localizationHelper;
private final NumberFormatter numberFormatter;
public CurrencyFormatter(final LocalizationHelper localizationHelper, final NumberFormatter numberFormatter) {
this.localizationHelper = localizationHelper;
this.numberFormatter = numberFormatter;
}
public String prettyPrint(final Currency amount) {
}
}
CurrencyUtilFactory
public class CurrencyUtilFactory {
@Autowired
private NumberFormatter numberFormatter;
public CurrencyUtil create() {
...
final LocalizationHelper localizationHelper = ....;
return new CurrencyUtil(localizationHelper, numberFormatter)();
}
}
的NumberFormatter
@Component
public class NumberFormatter {}
PS:为这个例子道歉:)
答案 0 :(得分:2)
下面的代码片段能为您效果吗?这样,您可以重复CurrencyUtil
使用不同的amount
值。
@Component
public class CurrencyUtil {
private final NumberFormatter numberFormatter;
@Autowired
public CurrencyFormatter(NumberFormatter numberFormatter) {
this.numberFormatter = numberFormatter;
}
public String prettyPrint(Currency amount) {
// ...
}
}
更新(根据调整后的问题)
Spring只能自动装配它知道的bean。如果你的bean(或其中一些)不是用Spring管理的,你必须自己自动装配它们(例如通过构造函数)。解决方案可能是:
@Configuration
public class AppConfig {
@Autowired
private NumberFormatter numberFormatter;
@Autowired
private LocalizationHelper localizationHelper;
@Bean
public CurrencyUtil curencyUtil() {
return new CurrencyUtil(localizationHelper, numberFormatter);
}
// ...
}
或
@Component
public class CurrencyUtil {
private LocalizationHelper helper;
private NumberFormatter numberFormatter;
@Autowired
public CurrencyFormatter(LocalizationHelper helper, NumberFormatter numberFormatter) {
this.helper = helper;
this.numberFormatter = numberFormatter;
}
public String prettyPrint(Currency amount) {
// ...
}
}