I can't make method level validation right. Or I don't understand how it works.
My application class is below. Very simple. It contains MethodValidationPostProcessor bean definition. It also runs Greeter service.
@SpringBootApplication
public class App implements CommandLineRunner {
private final Greeter greeter;
public App(Greeter greeter) {
this.greeter = greeter;
}
public static void main(String[] args) {
new SpringApplicationBuilder().main(App.class).sources(App.class).web(false).run(args).close();
}
@Bean
public org.springframework.validation.beanvalidation.MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
@Override
public void run(String... args) throws Exception {
final Input input = new Input();
input.setName("j");
final String messageFromInput = greeter.getMessageFromInput(input);
final String messageFromString = greeter.getMessageFromString("j");
}
}
Greeter service below. Here I do expect to validate input and output.
@Service
@Validated
public class Greeter {
String getMessageFromInput(@Valid @NotNull Input name) {
return "[From Input] Greetings! Oh mighty " + name + "!";
}
String getMessageFromString(@Size(min = 4) String name) {
return "[From String] Greetings! Oh mighty " + name + "!";
}
}
Input DTO is very simple as well.
public class Input {
@NotEmpty
@Size(min = 3)
private String name;
// Getters, setters and toString ommited.
}
Since the name in both cases, direct String and DTO, is only one letter I expect this setup to throw exception. Unfortunately, nothing happens and application completes successfully. It works with controller's methods. But I would like it to work with any bean's methods.
Greeteras a constructor argument. I guess this is triggering early creation of the bean, making it not a candidate for proxy creation anymore and hence validation isn't applied. Create a@Beanmethod which creates theCommandLineRunnerand inject theGreeteras a method argument instead. Also make your methodspublicas AOP will only work on public methods.Greeteras an argument it works fine. It seems that Greeter'spublicmethods access is irrelevant. Now when you mentioned about it, I remember info in log file saying that Greeter is not eligible candidate for proxy. Now I know what the implications are.