10

I have a class that is an entity:

Class.java

@Entity
public class Class {
    @Id
    @GeneratedValue
    private Long id;

    @NotNull
    @Range(min = 0, max = 10)
    private double value;
}

I want to get rid of the hard-coded values from the @Range annotation and load them from a configuration file.

constraints.properties

minVal=0
maxVal=10

This is what I've tried:

@Component
@Entity
@PropertySource("classpath:/constraints.properties")
public class Class {

    @Value("${minVal}")
    private final long minValue;
    @Value("${maxVal}")
    private final long maxValue;

    @Id
    @GeneratedValue
    private Long id;

    @NotNull
    @Range(min = minValue, max = maxValue)
    private double value;
}

The error I get is attribute value must be constant. How the initialization of these fields should be performed to get the result I want?

RK1
  • 429
  • 2
  • 7
  • 28
  • 1
    As mentioned in the answer, what you're trying to do is likely impossible. However if you need to validate range against some value from Spring configuration you could write custom validator and inject the min and max value to it. It would involve more code than just a single annotation, so the effort might not be worth it, but if you really need it, it might be a way to go – Bohuslav Burghardt Nov 07 '15 at 20:44

1 Answers1

10

First: to inject values into a final field you have to use constructor injection see this question

This means that you pass some unknown value into the constructor.

Although the value never changes it is not constant, since the compiler cannot know this value, because its determined at runtime. And you can only use expressions as values of annotation whose value can be determined at compile time.

Thats because annotations are declared for a class not for a single instance and in your example the values of the variables are potentially diffrent for every instance.

So I would say, that what you want to achieve is not possible.

Community
  • 1
  • 1
wastl
  • 2,643
  • 14
  • 27