Spring Boot @ConfigurationProperties Property Validation

In the previous post you have learn different way for how to read application.properties in spring boot . Now in this post we Validate Properties Files At Startup in Spring Boot . We will use @Validate annotation for validation .

Application.properties

email.username=javavogue
email.pwd=12345
email.poolsize=6

EmailConfig.java

package com.javavogue.demo.service;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

@Component
@ConfigurationProperties("email")
@Validated
public class EmailConfig {
     
   private String   username;
     
    private String  pwd;
    
    @Min(5)
    @Max(10)
    private int poolsize;
	
    public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	
	public int getPoolsize() {
		return poolsize;
	}
	
	public void setPoolsize(int poolsize) {
		this.poolsize = poolsize;
	}
		
}

We have explained  Spring Boot @ConfigurationProperties Property Validation here . If you will pass invalid values in properties file application through error on the startup .  Now we will change email.poolsize value to 20 then it will through error .

email.username=javavogue
email.pwd=12345
email.poolsize=20

Error :

Error starting ApplicationContext. To display the conditions report re-run your application with ‘debug’ enabled.
2020-04-18 14:00:12.017 ERROR 4072 — [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :

***************************
APPLICATION FAILED TO START
***************************

Description:

Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under ’email’ to com.javavogue.demo.service.EmailConfig failed:

Property: email.poolsize
Value: 20
Origin: class path resource [application.properties]:3:16
Reason: must be less than or equal to 10

Action:

Update your application’s configuration

 

It means that Spring Boot @ConfigurationProperties Property Validation working properly .

 

Leave a Reply

Your email address will not be published. Required fields are marked *

13 + = 20