简体   繁体   中英

How to import value from properties file and use it in annotation?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM