Marcin Szałek
Marcin Szałek

Reputation: 5069

Is it possible to get custom object from spring application properties?

Is it possible to get own object from application.yaml and bind it with @Value to my component?

Model:

@Data
public class CurrencyPlan {
    private String id;
    private String basePrice;
    private String merchantId;
}

application.yml:

plans:
  eur:
    id: id
    basePrice: 5
    merchantId: someid

What I'm trying to do:

@Value("${plans.eur}") CurrencyPlan eurPlan

What I get:

java.lang.IllegalArgumentException: Could not resolve placeholder 'plans.eur' in value "${plans.eur}"

Is this even possible? And if so, how to do it? I'm pretty out of ideas :(

Thanks in advance ;)

Upvotes: 4

Views: 6899

Answers (1)

Darren Forsythe
Darren Forsythe

Reputation: 11421

If you're looking to bind your properties to a class you can use @ConfigurationProperties.

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-typesafe-configuration-properties

@ConfigurationProperties(prefix="plans.eur") and @Component would be placed on the CurrencyPlan. @EnableConfigurationProperties preferably placed on an @Configuration class.

After you can autowire the CurrencyPlan class into the dependent classes.

Upvotes: 6

Related Questions