【问题标题】:Int from application.properties来自 application.properties 的整数
【发布时间】:2021-01-28 13:48:47
【问题描述】:

在 application.properties 中:

comment.length=3000

现在我想使用这个常量:

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

编译时出现这个错误:

java:不兼容的类型:java.lang.String 无法转换为 int

【问题讨论】:

  • 好的,首先,您的实体客户端不是 Spring Bean,因此您无法注入属性值。其次,如果你想将 Spring Properties 注入到 Spring Bean 中,你应该使用 @Value

标签: java spring jpa


【解决方案1】:

这与How to import value from properties file and use it in annotation? 的重复非常接近,但我认为问题之间存在细微差别。

您正在尝试使用${comment.length} 引用@Column 注释中的属性。真正发生的是您尝试将 String "${comment.length}" 分配给注释的 length 属性。这当然是不允许的,它需要一个int

Java 或 Spring 不能“神奇地”用属性替换 ${propertyName}。然而,Spring 有 its own way of injecting property values:

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

即使你的实体是一个 Spring bean(例如用 @Component 注释),并且你用 @Value 注入了属性,它也不能在注释中使用。这是因为注解中的值需要保持不变,在accepted answer to the near duplicate question 中有更详细的说明。

现在我想使用这个常量:

它根本不是一个常数,它是在运行时确定的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-30
    • 1970-01-01
    • 2019-07-17
    相关资源
    最近更新 更多