Saturday 4 August 2018

Spring Boot: Validating properties

If you annotate @ConfigurationProperties classes with @Validated annotation, then spring boot validate the properties.

@Component
@ConfigurationProperties
@Validated
public class MyConfigurations {

         @NotEmpty
         private String appName;
        
         ......
         ......
        
}

As you see above code, @NotEmpty annotation, makes sure that the appName must not be empty.

Find the below working application.

application.properties
appName=
version=1.25

MyConfigurations.java
package com.sample.myApp.model;

import javax.validation.constraints.NotEmpty;

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

@Component
@ConfigurationProperties
@Validated
public class MyConfigurations {

 @NotEmpty
 private String appName;
 private double version;

 public String getAppName() {
  return appName;
 }

 public void setAppName(String appName) {
  this.appName = appName;
 }

 public double getVersion() {
  return version;
 }

 public void setVersion(double version) {
  this.version = version;
 }
}


Application.java
package com.sample.myApp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import com.sample.myApp.model.MyConfigurations;

@SpringBootApplication
public class Application {

 public static void main(String[] args) {
  ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args);

  MyConfigurations myConfiguration = applicationContext.getBean(MyConfigurations.class);

  System.out.println("****************************************************");
  System.out.printf("Application Name : %s\n", myConfiguration.getAppName());
  System.out.printf("Version : %f\n", myConfiguration.getVersion());
  System.out.println("****************************************************");

  applicationContext.close();

 }

}

When you ran above application, you will endup in below validation failure.
***************************
APPLICATION FAILED TO START
***************************

Description:

Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under '' to com.sample.myApp.model.MyConfigurations failed:

    Property: .appName
    Value: 
    Origin: class path resource [application.properties]:2:0
    Reason: must not be empty


Action:

Update your application's configuration

Spring boot supports all the annotations in 'javax.validation.constraints' package.


Project structure looks like below.




Previous                                                 Next                                                 Home

No comments:

Post a Comment