4

I have read similar post in the forum but actually could not find an answer. I am reading a property from an application.yaml file but I want to make that variable final. But compiler does not allow me to do it and says the variable might not be initialized. What I want to do is to use final as below. So this variable is defined in a controller class.

 @Value("${host.url}")
 private final String url;

So how can I do it final ?

user1474111
  • 1,356
  • 3
  • 23
  • 47
  • You cannot. The only way to make this work is put the `@Value` annotation on an attribute int he constructor and then set the `url` in the constructor. – M. Deinum Oct 30 '19 at 11:04
  • https://stackoverflow.com/questions/7130425/spring-property-injection-in-a-final-attribute-value-java – Shailesh Chandra Oct 30 '19 at 11:04

1 Answers1

10

The only way to achieve it is using constructor injection.

@Component
public class MyBean {

    private final String url;

    public MyBean(@Value("${host.url}") String url) {
        this.url = url;
    }
}
cassiomolin
  • 124,154
  • 35
  • 280
  • 359