Spring Boot @ConfigurationProperties example
Spring Boot @ConfigurationProperties is allows developer to map the entire property file into an
object easily.
In normal spring framework, we use @Value annotation to inject property values one by one as shown below:
@Value("${cmdb.resource-url}")
private int threadPool;
|
With the use of @ConfigurationProperties, it is going to be much easier. Here is a simple property file
"application.properties":
cmdb.resource-url=http://java2novice.com
cmdb.resourcePort[0]=80
cmdb.resourcePort[1]=443
|
@ConfigurationProperties annotation helps to load a family of related properties, say in this specific case
namespaced by the prefix conveniently named "cmdb".
The approach Spring boot takes is to define a bean that can hold all the families of related properties this way:
package com.java2novice.springboot.util;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties("cmdb")
public class CmdbProperties {
private String resourceUrl;
private List<Integer> resourcePort;
@Override
public String toString() {
return "resourceUrl: "+ this.resourceUrl+"\n"
+ "resourcePort: "+this.resourcePort+"\n";
}
public String getResourceUrl() {
return resourceUrl;
}
public void setResourceUrl(String resourceUrl) {
this.resourceUrl = resourceUrl;
}
public List<Integer> getResourcePort() {
return resourcePort;
}
public void setResourcePort(List<Integer> resourcePort) {
this.resourcePort = resourcePort;
}
}
|
During runtime, all the properties will be injected to the related bean attributes.
Now lets print the properties after application load:
package com.java2novice.springboot;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.java2novice.springboot.util.CmdbProperties;
@SpringBootApplication
public class SpringBootWebApplication {
private static Logger logger = LoggerFactory.getLogger(SpringBootWebApplication.class);
@Autowired
private CmdbProperties cmdbProperties;
public static void main(String[] args) throws Exception {
SpringApplication.run(SpringBootWebApplication.class, args);
}
@PostConstruct
public void init() {
logger.info(cmdbProperties.toString());
}
}
|
Console Output
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.2.RELEASE)
2017-10-20 17:33:46.786 INFO 49754 --- [ main] c.j.springboot.SpringBootWebApplication : resourceUrl: http://java2novice.com
resourcePort: [80, 443]
|
|