【问题标题】:Injecting filed value using @Value() in Spring Boot?在 Spring Boot 中使用 @Value() 注入字段值?
【发布时间】:2020-09-16 07:14:36
【问题描述】:

所以我有一些自定义 POJO。当我通过空构造函数实例化该对象时,我希望随时将其归档的fee 初始化为来自application.properties 的某个预设值。

在我的application-prod.properties:

fee=1500

我的 POJO 类:

public class PenaltyWithNoInvoiceDto {
    
    private int penatltyId; 
    private int number; 
    private String projectName;
    
    @Value("${fee}")
    private float fee;
    
    public PenaltyWithNoInvoiceDto() {
        
    }
    
    public PenaltyWithNoInvoiceDto(int penatltyId, int number, String projectName) {
        super();
        this.penatltyId = penatltyId;
        this.number = number;
        this.projectName = projectName;
    }
}

在我的@Service 类中,我使用空构造函数实例化PenaltyWithNoInvoiceDto。但是当我打印fee 字段时,我得到了零。

如何使该字段的值为 1500,我从 application-prod.properties 获得该值?

【问题讨论】:

标签: spring-boot environment-variables


【解决方案1】:

@Value 注解只会在 Spring 管理 bean 的生命周期时应用 - 例如,当 bean 使用 @Component@Service 等注解或由 @ 的 @Bean 方法实例化时987654325@上课。当您在自己的代码中执行new PenaltyWithNoInvoiceDto() 时,它不会被应用。

您可以将@Value("${fee}") 添加到@Service 类的字段中,然后在使用new PenaltyWithNoInvoiceDto(fee) 之类的内容实例化它时将其传递给DTO。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 2016-01-26
    • 1970-01-01
    • 2019-04-30
    • 2022-08-22
    • 2017-10-15
    • 2018-09-01
    相关资源
    最近更新 更多