user544192
user544192

Reputation: 715

Spring - Inject few fields that are not passed through the constructor

I've got three classes. CurrencyUtil needs NumberFormatter. NumberFormatter is injected into CurrencyUtilFactory only because CurrencyUtil needs it.

Is there a way to inject NumberFormatter directly into CurrencyUtil?

Thanks!

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: Apologies for this made up example :)

Upvotes: 0

Views: 105

Answers (1)

pgiecek
pgiecek

Reputation: 8220

Could something like the snippet below work for you? This way you can reuse CurrencyUtil with different amount values.

@Component
public class CurrencyUtil {

    private final NumberFormatter numberFormatter;

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

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

Update (based on the adjusted question)

Spring can autowire only beans that it knows. If your beans (or some of them) are not managed with Spring, you have to autowire them on your own (e.g. via a constructor as you did). The solution could be:

@Configuration
public class AppConfig {

    @Autowired
    private NumberFormatter numberFormatter;

    @Autowired
    private LocalizationHelper localizationHelper;

    @Bean
    public CurrencyUtil curencyUtil() {
        return new CurrencyUtil(localizationHelper, numberFormatter);
    }

    // ...
}

Or

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

Upvotes: 2

Related Questions