如何从属性文件中导入值并在注释中使用它? [英] How to import value from properties file and use it in annotation?

查看:102
本文介绍了如何从属性文件中导入值并在注释中使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体类:

Class.java

Class.java

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

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

我想摆脱<$ c中的硬编码值$ c> @Range 注释并从配置文件加载它们。

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

constraints.properties

constraints.properties

minVal=0
maxVal=10

这是我尝试过的:

@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.

这篇关于如何从属性文件中导入值并在注释中使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆