Monday, December 2, 2019

spring annotations i never had the chance to use part 2: @ConfigurationProperties

Few days ago, I accidentally stumbled upon a Spring annotation from Spring Boot project while I was checking something else.

We all know how to bind property values with "@Value" to the classes and we all know that this can be quite cumbersome if there are multiple properties to bind. Spring Boot is here to help. You can use "@ConfigurationProperties" and bind multiple values quite concisely. We will give a prefix to differentiate other configs from ours. e.g. "@ConfigurationProperties(prefix = "jdbc")".
Any field this annotated class has is populated with property values from the property resource. For instance if it has a username parameter then property resource with "jdbc.username" key will populate this field. The most practical way of using this annotation is using it with "@Configuration".


You can check how we create the config class.
01package com.sezinkarli.tryconfigprops;
02 
03import org.springframework.boot.context.properties.ConfigurationProperties;
04import org.springframework.context.annotation.Configuration;
05 
06import javax.annotation.PostConstruct;
07import java.util.HashMap;
08import java.util.Map;
09 
10@Configuration
11@ConfigurationProperties(prefix = "jdbc")
12public class JdbcConfig
13{
14    private String user;
15    private String password;
16    private String url;
17    private String driver;
18 
19    public String getUser()
20    {
21        return user;
22    }
23 
24    public void setUser(String user)
25    {
26        this.user = user;
27    }
28 
29    public String getPassword()
30    {
31        return password;
32    }
33 
34    public void setPassword(String password)
35    {
36        this.password = password;
37    }
38 
39    public String getUrl()
40    {
41        return url;
42    }
43 
44    public void setUrl(String url)
45    {
46        this.url = url;
47    }
48 
49    public String getDriver()
50    {
51        return driver;
52    }
53 
54    public void setDriver(String driver)
55    {
56        this.driver = driver;
57    }
58 
59    public String getProperty(String key)
60    {
61        return propertyMap.get(key);
62    }
63}
And below you can check the properties we map from application properties
jdbc.user=myJdbcUser
jdbc.password=myPwd
jdbc.url=myUrl
jdbc.driver=myJdbcDriver
After that you can easily get these values by injecting the configuration class to somewhere.
1@Service
2public class YourService
3{
4 
5    @Autowired
6    private JdbcConfig jdbcConfig;
7}
You can also check here for a working toy project using "@ConfigurationProperties".