Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject value from properties in Spring Boot

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?

like image 425
rodor Avatar asked Oct 28 '25 16:10

rodor


1 Answers

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;
 }
}
like image 121
Arpit Aggarwal Avatar answered Oct 30 '25 07:10

Arpit Aggarwal