Basic properties handling - Part 3
16.03.2018 by Jens in Spring Boot | Newsletter
Using @Value to inject properties is fine as long as it is just a handful. When we have more, and they are grouped around a single configuration entity like all props for a remote connection, we can introduce a configuration class using the @ConfigurationProperties annotation of Spring Boot.
We can mark a simple POJO with it and Spring Boot map properties to fields of the class.
@ConfigurationProperties("cb") public class CBProperties { private boolean enabled; private int timeout; private String host; // standard getters and setters }
The parameter @ConfigurationProperties accepts, is the prefix for our properties. The keys of the example above look like:
- cb.enabled
- cb.timeout
We can inject this class like any other Spring Bean.
However, before we can use this feature, we must enable it on one of our @Confiuration classes by adding the @EnableConfigurationProperties annotation and give it the name of our config property class like:
@Configuration @EnableConfigurationProperties(CBProperties.class) public class MyConfiguration { }
Voila!
Nice, isn’t it? And it even supports nested classes.
comments powered by Disqus