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.
package com.sezinkarli.tryconfigprops;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Configuration
@ConfigurationProperties(prefix = "jdbc")
public class JdbcConfig
{
    private String user;
    private String password;
    private String url;
    private String driver;

    public String getUser()
    {
        return user;
    }

    public void setUser(String user)
    {
        this.user = user;
    }

    public String getPassword()
    {
        return password;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }

    public String getUrl()
    {
        return url;
    }

    public void setUrl(String url)
    {
        this.url = url;
    }

    public String getDriver()
    {
        return driver;
    }

    public void setDriver(String driver)
    {
        this.driver = driver;
    }

    public String getProperty(String key)
    {
        return propertyMap.get(key);
    }
}

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.
@Service
public class YourService
{

    @Autowired
    private JdbcConfig jdbcConfig;
}
You can also check here for a working toy project using "@ConfigurationProperties".