Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...