Reputation: 2858
I use @AssertTrue
annotation to ensure the execution of a method that sets some default values (always returns true). These set values are validated as @NotEmpty
(these are Strings). So I need to guarantee that method annotated with @AssertTrue
is executed strictly before that fields annotated with @NotEmpty
.
Simplified code example (not included Hibernate annotations):
public class MyClass {
@NotEmpty
private String myField = null;
@SuppressWarnings("unused")
@AssertTrue
private boolean fillDefaultValues() {
if (this.myField == null) {
this.myField = "default value";
}
return true;
}
}
Upvotes: 0
Views: 1561
Reputation: 2858
Finally I have solved my problem.
Debuging validator stack trace, I have seen that first it process beanValidators, and then, memberValidators. So the only I have to do is define my initialization code in a class constraint.
I have defined a new class annotation where, depending on the type of the pojo received, I set default values.
I have verified that this code is executed before than any other (member) constarint, like @NotEmpty, etc.
Upvotes: 0
Reputation: 597362
This seems to me like a hack. For two reasons:
The thing in common is "initialization code". In order to achieve what you want, you can register a listener and execute the initialization method before the validation happens. Here's the documentation of hibernate-validator - it tells you about event listeners.
You can also manually set the default values in your service layer (since you seem to be using anemic data model). Since this seems like a business logic, it'd better be in the service method, before the object is persisted.
Upvotes: 1