[英]How to import value from properties file and use it in annotation?
I have a class that is an entity: 我有一个实体类:
Class.java 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. 我想摆脱@Range
注释中的硬编码值并从配置文件中加载它们。
constraints.properties 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
. 我得到的错误是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. 虽然值永远不会改变但它不是constant
,因为编译器无法知道这个值,因为它在运行时确定。 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. 所以我想说,你想达到的目标是不可能的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.