Close

Spring Framework - Method Validations Examples

Spring Framework 

package com.logicbig.example;

import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotEmpty;

public class User {
@NotEmpty
private String name;
@Email
private String email;

public String getName() {
return name;
}

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

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", email='" + email + '\'' +
'}';
}
}
package com.logicbig.example;

import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;

@Component
@Validated
public class UserTask {

public void registerUser(@NotNull @Valid User user){
System.out.println("registering user: "+ user);
}
}
package com.logicbig.example;

import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import jakarta.validation.constraints.FutureOrPresent;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import java.time.LocalDateTime;

@Validated
@Component
public class ReportTask {
public @Pattern(regexp = "[0-3]") String createReport(@NotNull @Size(min = 3, max = 20) String name,
@NotNull @FutureOrPresent LocalDateTime startDate) {
return "-1";
}
}

package com.logicbig.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validator;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.Set;

@Configuration
@ComponentScan
public class AppConfig {
@Bean
public Validator validatorFactory() {
return new LocalValidatorFactoryBean();
}

@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}

public static void main(String[] args) {
ApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);

ReportTask task = context.getBean(ReportTask.class);
System.out.println("-- calling ReportTask#createReport() --");
System.out.println("-- with invalid parameters --");
try {
String status = task.createReport("", LocalDateTime.now().minusMinutes(30));
System.out.println(status);
} catch (ConstraintViolationException e) {
printValidationError(e);
}
System.out.println("-- with valid parameters but invalid return value --");
try {
String status = task.createReport("create reports", LocalDateTime.now().plusMinutes(30));
System.out.println(status);
} catch (ConstraintViolationException e) {
printValidationError(e);
}

UserTask userTask = context.getBean(UserTask.class);
System.out.println("-- calling UserTask#registerUser() --");
User user = new User();
user.setEmail("tony-example.com");
try {
userTask.registerUser(user);
} catch (ConstraintViolationException e) {
printValidationError(e);
}
}

private static void printValidationError(ConstraintViolationException e) {
System.out.println("validation errors:");
e.getConstraintViolations().stream().sorted(Comparator.comparing(v->v.getPropertyPath().toString()))
.map(v -> v.getMessage()).forEach(System.out::println);
}
}

Output

-- calling ReportTask#createReport() --
-- with invalid parameters --
validation errors:
size must be between 3 and 20
must be a date in the present or in the future
-- with valid parameters but invalid return value --
validation errors:
must match "[0-3]"
-- calling UserTask#registerUser() --
validation errors:
must be a well-formed email address
must not be empty
Original Post




See Also