Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Micronaut: Validate bean method parameters

We can apply validations on methods of any class declared as a Micronaut bean by applying javax.validation annotations.

 

Example

@Singleton
public class Employee {

private int id;
private String name;
private int age;

public void setId(@Positive int id) {
this.id = id;
}

public void setName(@NotBlank String name) {
this.name = name;
}

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

}

In the above example,

a.   @Positive annotation will be validated when invoking setId, setAge methods.

b.   @NotBlank annotation will be validated when invoking the setName method.

 

Find the below working application.

 

Step 1: Create new maven project ‘micronaut-validate-method-params’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

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.0modelVersion>
groupId>com.sample.appgroupId>
artifactId>micronaut-validate-method-paramsartifactId>
version>1version>

properties>
maven-compiler-plugin.version>3.8.1maven-compiler-plugin.version>
micronaut.version>3.7.3micronaut.version>
slf4j.version>2.0.3slf4j.version>

maven.compiler.target>15maven.compiler.target>
maven.compiler.source>15maven.compiler.source>
properties>

dependencies>

dependency>
groupId>io.micronautgroupId>
artifactId>micronaut-inject-javaartifactId>
version>${micronaut.version}version>
dependency>
dependency>
groupId>io.micronautgroupId>
artifactId>micronaut-runtimeartifactId>
version>${micronaut.version}version>
dependency>

dependency>
groupId>io.micronautgroupId>
artifactId>micronaut-validationartifactId>
version>${micronaut.version}version>
dependency>


dependency>
groupId>org.slf4jgroupId>
artifactId>slf4j-apiartifactId>
version>${slf4j.version}version>
dependency>
dependency>
groupId>org.slf4jgroupId>
artifactId>slf4j-simpleartifactId>
version>${slf4j.version}version>
dependency>
dependencies>

build>
plugins>

plugin>
artifactId>maven-assembly-pluginartifactId>
configuration>
archive>
manifest>
mainClass>com.sample.app.AppmainClass>
manifest>
archive>
descriptorRefs>
descriptorRef>jar-with-dependenciesdescriptorRef>
descriptorRefs>
configuration>

executions>
execution>
id>make-assemblyid>
phase>packagephase>
goals>
goal>singlegoal>
goals>
execution>
executions>
plugin>

plugins>
build>
project>

Step 3: Define Employee class.

 

Employee.java

package com.sample.app.model;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Positive;

import jakarta.inject.Singleton;

@Singleton
public class Employee {

private int id;
private String name;
private int age;

public int getId() {
return id;
}

public void setId(@Positive int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(@NotBlank String name) {
this.name = name;
}

public int getAge() {
return age;
}

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

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", age=" + age + "]";
}


}

Step 4: Define main application class.

 

App.java 

package com.sample.app;

import com.sample.app.model.Employee;

import io.micronaut.context.ApplicationContext;

public class App {

public static void main(String[] args) {
try (ApplicationContext applicationContext = ApplicationContext.run()) {

Employee emp = applicationContext.getBean(Employee.class);

System.out.println("Set employee name to blank");
try {
emp.setName("");
} catch (Exception e) {
e.printStackTrace();
}

System.out.println("\nSet employee id to -1");
try {
emp.setId(-1);
} catch (Exception e) {
e.printStackTrace();
}

System.out.println("\nSet employee age to 0");
try {
emp.setAge(0);
} catch (Exception e) {
e.printStackTrace();
}

emp.setAge(34);
emp.setId(1);
emp.setName("Krishna");

System.out.println("\nemp : " + emp);
}

}
}

 

Total project structure looks like below.


Build the project using mvn package command.

Navigate to the folder where pom.xml is located and execute the command ‘mvn package’.

 

Upon command successful execution, you can see the jar file ‘micronaut-validate-method-params-1-jar-with-dependencies.jar’ in project target folder.

$ls ./target/
archive-tmp
classes
generated-sources
maven-archiver
maven-status
micronaut-validate-method-params-1-jar-with-dependencies.jar
micronaut-validate-method-params-1.jar
test-classes

Execute below command to run the application.

$java -jar ./target/micronaut-validate-method-params-1-jar-with-dependencies.jar
Set employee name to blank
javax.validation.ConstraintViolationException: setName.name: must not be blank
at io.micronaut.validation.ValidatingInterceptor.intercept(ValidatingInterceptor.java:111)
at io.micronaut.aop.chain.MethodInterceptorChain.proceed(MethodInterceptorChain.java:137)
at com.sample.app.model.$
Employee$Definition$Intercepted.setName(Unknown Source)
at com.sample.app.App.main(App.java:16)

Set employee id to -1
javax.validation.ConstraintViolationException: setId.id: must be greater than 0
at io.micronaut.validation.ValidatingInterceptor.intercept(ValidatingInterceptor.java:111)
at io.micronaut.aop.chain.MethodInterceptorChain.proceed(MethodInterceptorChain.java:137)
at com.sample.app.model.$Employee$Definition$Intercepted.setId(Unknown Source)
at com.sample.app.App.main(App.java:23)

Set employee age to 0
javax.validation.ConstraintViolationException: setAge.age: must be greater than 0
at io.micronaut.validation.ValidatingInterceptor.intercept(ValidatingInterceptor.java:111)
at io.micronaut.aop.chain.MethodInterceptorChain.proceed(MethodInterceptorChain.java:137)
at com.sample.app.model.$
Employee$Definition$Intercepted.setAge(Unknown Source)
at com.sample.app.App.main(App.java:30)

emp : Employee [id=1, name=Krishna, age=34]

You can download the application from this link.


 

Previous                                                    Next                                                    Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Micronaut: Validate bean method parameters

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×