Search code examples
jakarta-eehibernate-validator

how to pass web.xml parameters to annotations (hibernate validator )?


I want to pass context params on web.xml to hibernate annotations in a Java Bean, for example:

web.xml :

<context-param>
 <param-name>limit</param-name>
 <param-value>5</param-value>
</context-param>

Java Bean :

@Length(min=0, max=limit )
private String text;

Is this possible ?


Solution

  • The short answer is that it is not possible. The constraint annotations are static, you cannot dynamically change them.

    In the best case you could try writing a custom constraint. You can still not use a variable in the constraint, but in the ConstraintValidator implementation you could access some dynamic state, either via injection or via a ThreadLocal. Of course it is now not possible anymore to defer the exact constraints by looking at the domain model.

    If you need to alter constraints depending on in which application your model gets used, I think I would prefer to use Bean Validation's XML configuration.