gpt4 book ai didi

java - Spring - 注入(inject)一些未通过构造函数传递的字段

转载 作者:行者123 更新时间:2023-12-02 03:40:23 24 4
gpt4 key购买 nike

我有三节课。CurrencyUtil 需要 NumberFormatterNumberFormatter 被注入(inject)到 CurrencyUtilFactory 中只是因为 CurrencyUtil 需要它。

有没有办法将NumberFormatter直接注入(inject)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)();
}

}

数字格式化程序

@Component
public class NumberFormatter {}

PS:对这个虚构的例子表示歉意:)

最佳答案

类似下面的代码片段对您有用吗?这样您就可以使用不同的 amount 值重复使用 CurrencyUtil

@Component
public class CurrencyUtil {

private final NumberFormatter numberFormatter;

@Autowired
public CurrencyFormatter(NumberFormatter numberFormatter) {
this.numberFormatter = numberFormatter;
}

public String prettyPrint(Currency amount) {
// ...
}
}

更新(基于调整后的问题)

Spring 只能 Autowiring 它知道的 bean。如果你的bean(或其中一些)不是用Spring管理的,你必须自己 Autowiring 它们(例如通过构造函数,就像你所做的那样)。解决方案可能是:

@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) {
// ...
}
}

关于java - Spring - 注入(inject)一些未通过构造函数传递的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36907285/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com