1

I have a spring component that validates the values of an Entity Class,

One of the variables has a Custom Annotation whose values are supposed to be loaded from the property file, currently it says that Attribute must be constant

Here is the sample code.

I know that Spring allows to fetch properties like this

@Value("${allowedNames}")
    private String names;

But I have an entity with one of the variables annotated by custom validator interface i.e. @NameValidationDefinition. I would like to pass the values from the properties file to the annotation but it gives compile time error that Attribute must be Constant which I understand as I know that

Annotations take only constants or final and static declared primitives or Strings
public Class Person {
@NameValidationDefinition(values = names)
private String name;
}

What I want to know is that is there a workaround for this to make it work?

The value from the properties file is by default casted to String but still when I create the Entity and initialize the variable as static final and pass the String in the Constructor, I get the same compile time error.

I would appreciate any kind of help on this.

Nick Div
  • 5,338
  • 12
  • 65
  • 127

1 Answers1

1

You cannot have variables in annotations. That's not a limitation of Bean Validation, but of the JVM itself. See also Which types can be used for Java annotation members?

Note, in the Spring example you are giving the value is a string with a special "key" ${allowedNames} which later on gets interpolated. That's different from the value of the annotation being an actual variable as your code implies.

Community
  • 1
  • 1
Hardy
  • 18,659
  • 3
  • 49
  • 65
  • I hear you, and I am aware that anything but constants cannot ne passed to annotations but I was thinking if there was a hacky way of doing it. I mean developers bend the rules all the time with the code. – Nick Div Jun 20 '16 at 14:25
  • No, not on this one. You would have to temper with the JLS itself. Not saying that it cannot be done, but I for sure would not like to go there. – Hardy Jun 20 '16 at 14:26
  • Haha, got you.. Thanks.. I guess I can mark this as an answer as it might help some else looking for this. – Nick Div Jun 20 '16 at 16:21