How to Validate Spring Boot Bean Programmatically or Manually


Spring boot creates a bean object in the rest controller and assigns value to the json string obtained from the client or browser. If the validator is enabled, the bean will be validated before the controller method is run.

In the real-time scenarios, all validations can not be performed before executing the controller method. The spring boot bean needs to be tested at a given point in time. Spring boot supports to programmatically validate the bean anywhere you need it. After making some adjustment on the data, the spring boot bean must be validated several times.

In this post we will cover how to programmatically / manually validate a spring boot bean according to the logic of the developers.



pom.xml file and dependency

The “spring-boot-starter-validation” dependency will include all the jars needed for the validation of the request body programmatically. The web application needs the dependence of “spring-boot-starter-browser.” This will allow the tomcat server and start as a web application. The default “spring-boot-starter-test” test dependency will be applied to pom.xml for the  unit testing.

If you have created a spring boot application, now you’re trying to incorporate the validation code, then add the “spring-boot-starter-validation” dependency to the pom.xml file. The complete pom.xml file will be as shown below.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.5.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.yawintutor</groupId>
	<artifactId>Spring-Application</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringBootValidation</name>
	<description>Spring Boot Project</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-validation</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>


Spring Boot Bean class to validate

The spring boot bean class is required to store the value obtained from the client or browser in json format. A spring boot bean class contains private variables and getter and setter method. The bean class has annotation for validating the data. In this example the annotation @Min is used to validate a student age.

Student.java

package com.yawintutor;

import javax.validation.constraints.Min;

public class Student {

	@Min(5)
	private int age;

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}


Validation code

Spring boot contains a Validator class that validates the bean. Auto-wire the Validator class to create an object. The validate api is used to validate the bean. The bean object is validated programmatically using this validate api and returns all the violation errors. Using those errors, programmers will determine the program’s alternate flow.

The controller class code shows how to programmatically validate the student bean using the validator class.

TestController.java

ackage com.yawintutor;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Validated
public class TestController {

	@Autowired
	Validator validator;

	@PostMapping("/student/")
	ResponseEntity<String> student(@RequestBody Student student) {

		System.out.println("start validation");
		Set<ConstraintViolation<Student>> constraintViolation = validator.validate(student);
		if (!constraintViolation.isEmpty()) {
			throw new ConstraintViolationException(constraintViolation);
		}
		System.out.println("end validation");

		return ResponseEntity.ok("Your age is " + student.getAge());
	}	
}	


How to Test Validation

To validate the request body, start the application on the spring boot. Call the curl command or import and run in postman tool. 

curl -X POST \
  http://localhost:8080/student/ \
  -H 'Cache-Control: no-cache' \
  -H 'Content-Type: application/json' \
  -H 'Postman-Token: 6f258a7f-d361-44f8-9c9b-b5bdc2828250' \
  -d '{"age":"5"}'

Output

Your age is 5

If the invalid json value is passed as part of url the validation will fail. The url below displays the curl command with invalid data.

curl -X POST \
  http://localhost:8080/student/ \
  -H 'Cache-Control: no-cache' \
  -H 'Content-Type: application/json' \
  -H 'Postman-Token: 6f258a7f-d361-44f8-9c9b-b5bdc2828250' \
  -d '{"age":"3"}'

Output

{
    "timestamp": "2020-03-27T17:13:38.309+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "age: must be greater than or equal to 5",
    "path": "/student/"
}



Related Articles

Leave a Reply

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