I have a Rest Controller in which I initialise a service like this :
class Config {
  @Value(${"number.of.books"})
  private final static String numberOfBooks;
}
class MyController  {
 private final Service myService = new ServiceImplementation(Config.numberOfBooks)
 public ResponseEntity methodA() { ... }
}
The numberOfBooks field has a initialisation value but when it's passed in the ServiceImplementation constructor it comes null.
I'm thinking I'm missing something obvious over here.
What is the mistake and which would be the best practice to inject a value from a property file into a constructor?
I recommend you to directly inject numberOfBooks in your ServiceImplementation, as follows:
public class ServiceImplementation implements Service {
  @Value("${number.of.books}")
  private String numberOfBooks;
}
Otherwise use setter injection for static variables, as follows:
@Component
class Config {
 public static String numberOfBooks;
 @Value("${number.of.books}")
 public void setNumberOfBooks(String numberOfBooks) {
    numberOfBooks = numberOfBooks;
 }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With