首页 > 解决方案 > Spring Boot没有拾取属性

问题描述

我有一个 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")
})

我错过了什么吗?

标签: javaspringspring-bootproperties

解决方案


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

您不能在此处使用弹簧表达式语言 (SpEl)。

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

例如。编写或扩展当前的 SequenceGenerator。有关详细信息,请参见此处:

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


推荐阅读