Spring - 注入几个未通过构造函数传递的字段

时间:2016-04-28 06:50:38

标签: java spring

我有三节课。 CurrencyUtil需要NumberFormatterNumberFormatter仅被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:为这个例子道歉:)

1 个答案:

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