Close

Spring Framework - Method Validations Examples

Spring Framework 

package com.logicbig.example;

import javax.validation.constraints.Email;
import javax.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 javax.validation.Valid;
import javax.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 javax.validation.constraints.FutureOrPresent;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.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 javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.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.err.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 --
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 --
must match "[0-3]"
-- calling UserTask#registerUser() --
must be a well-formed email address
must not be empty
validation errors:
validation errors:
validation errors:
Original Post




See Also