Spring Boot @ConfigurationProperties Property Validation
In the previous page, we have seen @ConfigurationProperties example. The @ConfigurationProperties support JSR-303 bean validation – javax.validation
Here is a simple property file
"application.properties":
cmdb.resource-url=http://java2novice.com
cmdb.resourcePort[0]=80
cmdb.resourcePort[1]=443
cmdb.resourceCount=10
|
Now lets introduce some validations to our instance members:
package com.java2novice.springboot.util;
import java.util.List;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties("cmdb")
public class CmdbProperties {
@NotEmpty
private String resourceUrl;
private List<Integer> resourcePort;
@Max(5)
@Min(0)
private Integer resourceCount;
@Override
public String toString() {
return "resourceUrl: "+ this.resourceUrl+"\n"
+ "resourcePort: "+this.resourcePort+"\n"
+ "resourceCount: "+this.resourceCount+"\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;
}
public Integer getResourceCount() {
return resourceCount;
}
public void setResourceCount(Integer resourceCount) {
this.resourceCount = resourceCount;
}
}
|
During runtime, all the properties will be injected to the related bean attributes along with the validations.
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
***************************
APPLICATION FAILED TO START
***************************
Description:
Binding to target resourceUrl: http://java2novice.com
resourcePort: [80, 443]
resourceCount: 10
failed:
Property: cmdb.resourceCount
Value: 10
Reason: must be less than or equal to 5
Action:
Update your application's configuration
|
|