user1474111
user1474111

Reputation: 1516

How to make final variable when @Value annotation is used

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 ?

Upvotes: 5

Views: 4617

Answers (1)

cassiomolin
cassiomolin

Reputation: 131117

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

Upvotes: 11

Related Questions