views:

164

answers:

2

Hi all.

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;
   }
}
+1  A: 

This seems to me like a hack. For two reasons:

  • you always return true and assert it for the sole purpose of executing an initialization code
  • you expect the framework to access and validate your bean in a specific order in order to execute an initialization code

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.

Bozho
A: 

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.

Alberthoven
while I haven't read the javax.validation specification, this behaviour could be implementation-specific, and even if you succeed here, on the next upgrade this behaviour might change, if it is not defined in the spec. As I said, it is not the correct way to do the initialization.
Bozho
Ok, perhaps that is no the correct way,but, what is the correct way? Since I don't know that way I use this one because it works.
Alberthoven
in my answer I posted a link to event listeners - check them out.
Bozho