-1

So I have some custom POJO. I want any time when I instantiate that object thorough empty constructor to have its filed fee initialized to some preset value from application.properties.

In my application-prod.properties:

fee=1500

My POJO class:

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;
    }
}

In my @Service class, I'm instantiating PenaltyWithNoInvoiceDtowith empty constructor. But when I print fee field, I get zero.

How do I make this field to have value of 1500, I get that value from application-prod.properties?

Wrapper
  • 794
  • 10
  • 25
  • You have to start your application with prod profile. https://stackoverflow.com/questions/40060989/how-to-use-spring-boot-profiles – ALex Sep 16 '20 at 07:33

1 Answers1

2

The @Value annotation will only be applied when Spring is managing the lifecycle of the bean - for example when the bean is annotated with @Component, @Service, etc or instantiated by a @Bean method of an @Configuration class. It won't be applied when you do new PenaltyWithNoInvoiceDto() in your own code.

You could add the @Value("${fee}") to a field of your @Service class and then pass it to the DTO when instantiating it with something like new PenaltyWithNoInvoiceDto(fee).

Scott Frederick
  • 4,184
  • 19
  • 22