Reading Monetary Amount from application.yml Spring boot

Viewed 177

I am trying to load a monetary amount from application.yml that has Currency and Amount like:

financeAmt:
        value: 10000
        currency: EUR

I want to use java Money API(javax.money) or any of its implementation e.g org.javamoney.moneta.Money

But Spring boot is not able to load the "financeAmt" with @ConfigurationProperties it is setting it is as null.

It works fine if i create a custom class with the vale and currency properties.

Any help how can load this money values without creating custom class and using java money api.

1 Answers

Spring Boot does not know how to convert a String to org.javamoney.moneta.Money. If you are not tied to the format you could provide a @ConfigurationPropertiesBinding and use a config setting like:

financeAmt:
  value: EUR 10000
import org.javamoney.moneta.Money;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesBinding;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties("finance-amt")
public class FinanceAmtConfig {
    private Money value;

    public Money getValue() {
        return value;
    }

    public void setValue(Money value) {
        this.value = value;
    }
}

@Component
@ConfigurationPropertiesBinding
class MoneyConverter implements Converter<String, Money> {
    @Override
    public Money convert(String source) {
        // Needs some error handling....
        return Money.parse(source);
    }
}

Or if you are tied to the config format you could just read the primitive values e.g. a String and a BigDecimal and build the Money instance explicitly.

Related