英文:
Int from application.properties
问题
在 application.properties 文件中:
comment.length=3000
现在我想要使用这个常量:
@Entity(name="clients_client")
public class Client {
@Column(length="${comment.length}")
private String comment;
}
在编译时,我得到了这个错误:
> java: 不兼容的类型:无法将 java.lang.String 转换为 int
英文:
In 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
答案1
得分: 0
这与 https://stackoverflow.com/questions/33586968/how-to-import-value-from-properties-file-and-use-it-in-annotation 非常接近,但我认为这两个问题之间存在微妙的差别。
您正试图通过使用${comment.length}
在@Column
注释中引用属性。实际发生的情况是,您尝试将String
"${comment.length}"
分配给注释的 length
属性。当然,这是不允许的,它期望一个 int
值。
Java 或 Spring 不能“神奇地”将${propertyName}
替换为属性值。然而,Spring 有一种自己的方法来注入属性值:
@Value("${value.from.file}")
private String valueFromFile;
即使您的实体是 Spring Bean(例如使用 @Component
注释标记),并且您使用 @Value
注入了属性,它也无法在注释中使用。这是因为注释中的值需要是常量,并且在接近重复问题的被接受回答中有更详细的解释。
现在我想使用这个常量:
它根本不是常量,它是在运行时确定的。
英文:
This is very close to being a duplicate of https://stackoverflow.com/questions/33586968/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}
. What is really happening is that you try to assign the String
"${comment.length}"
to the length
attribute of the annotation. This is of course not allowed, it expects an int
.
Java, or Spring, can not "magically" replace ${propertyName}
with a property. Spring, however, has its own way of injecting property values:
@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. 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论