【问题标题】:Spring Boot not picking up propertiesSpring Boot没有拾取属性
【发布时间】:2021-03-05 22:52:05
【问题描述】:

我有一个 Spring Boot 应用程序,我正在尝试将 application.properties 中的属性作为参数注释传递给 Entity 类,如下所示:

@Entity
public class Entity{

    @Id
    @SequenceGenerator(name = "entity_id_seq", sequenceName = "entity_id_seq", initialValue = "${start-seq}")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "dish_id_seq")
    private int id;

我的 application.properties 有:

start-seq=100000

但它不会编译说“不兼容的类型:java.lang.String 无法转换为 int”,无法识别表达式。我还尝试将带有 @Value 注释的这个属性传递给这样的变量:

@Value("${start-seq}")
private int startSeq;

但变量始终为 0。我的配置类之前确实有以下注释,但它仍然不起作用:

@Configuration
@EnableConfigurationProperties
@PropertySources({
        @PropertySource("classpath:application.properties")
})

我错过了什么吗?

【问题讨论】:

    标签: java spring spring-boot properties


    【解决方案1】:

    @SequenceGenerator 不是 Spring 注解。因此,spring 在实体创建过程中不会对此进行评估。

    这里不能使用spring表达式语言(SpEl)。

    如果你想配置这些,你必须为此使用 JPA 或 Hibernate 配置。

    例如。编写或扩展当前的 SequenceGenerator。详情请看这里:

    https://thorben-janssen.com/custom-sequence-based-idgenerator/

    【讨论】:

    • 谢谢!但是@Value 不给变量赋值呢?它应该有效,对吧?
    • 是的,但仅限于弹簧组件内。它在实体中不起作用。
    猜你喜欢
    • 1970-01-01
    • 2019-01-09
    • 2018-08-05
    • 1970-01-01
    • 2015-08-20
    • 2011-11-02
    • 1970-01-01
    • 2019-09-26
    • 2019-06-08
    相关资源
    最近更新 更多