简体   繁体   English

来自 application.properties 的 Int

[英]Int from application.properties

In application.properties:在 application.properties 中:

comment.length=3000

Now I'd like to use this constant:现在我想使用这个常量:

@Entity(name="clients_client")
public class Client {
    @Column(length="${comment.length}")
    private String comment;
}

When compiling, I get this error:编译时,我收到此错误:

java: incompatible types: java.lang.String cannot be converted to int java:不兼容的类型:java.lang.String 无法转换为 int

This is very close to being a duplicate of How to import value from properties file and use it in annotation?这非常接近于如何从属性文件导入值并在注释中使用它? , but I think there is a subtle difference between the questions. ,但我认为这些问题之间存在细微差别。

You are trying to refer to a property in the @Column annotation by using ${comment.length} .您正在尝试使用${comment.length}引用@Column注释中的属性。 What is really happening is that you try to assign the String "${comment.length}" to the length attribute of the annotation.真正发生的事情是您尝试将String "${comment.length}"分配给注释的length属性。 This is of course not allowed, it expects an int .这当然是不允许的,它需要一个int

Java, or Spring, can not "magically" replace ${propertyName} with a property. Java 或 Spring 不能“神奇地”用${propertyName}替换${propertyName} Spring, however, has its own way of injecting property values :然而,Spring 有自己的注入属性值的方式

@Value("${value.from.file}")
private String valueFromFile;

Even if your entity was a Spring bean (for example annotated with @Component ), and you injected the property with @Value , it cannot be used in the annotation.即使您的实体是 Spring bean(例如用@Component注释),并且您用@Value注入了属性,它也不能在注释中使用。 This is because values in annotations need to be constant, and is explained in more detail in the accepted answer to the near duplicate question .这是因为注释中的值需要保持不变,并且在对近重复问题公认答案中进行了更详细的解释。

Now I'd like to use this constant:现在我想使用这个常量:

It simply is not a constant, it is determined at runtime.它根本不是一个常数,它是在运行时确定的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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