Spring boot 在Spring Boot中使用@value()注入字段值?
所以我有一些定制的POJO。我希望在任何时候,当我通过空构造函数实例化该对象时,将其fieldSpring boot 在Spring Boot中使用@value()注入字段值?,spring-boot,environment-variables,Spring Boot,Environment Variables,所以我有一些定制的POJO。我希望在任何时候,当我通过空构造函数实例化该对象时,将其fieldfee初始化为application.properties中的某个预设值 在我的应用程序-prod.properties中: fee=1500 我的POJO课程: public class PenaltyWithNoInvoiceDto { private int penatltyId; private int number; private String pro
fee
初始化为application.properties
中的某个预设值
在我的应用程序-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管理bean的生命周期时才会应用@value
注释-例如,当bean使用@Component
,@Service
进行注释时,etc或由@Configuration
类的@Bean
方法实例化。当您在自己的代码中执行newpenaltywhithnoinvoicedto()
时,将不会应用此选项
您可以将
@Value(“${fee}”)
添加到@Service
类的字段中,然后在使用类似new penaltywhithnoinvoicedto(fee)
的内容实例化时将其传递给DTO。您必须使用prod profile启动应用程序。