Calling a method that has autowired values

Punter Vicky :

I have a method where I am injecting a value to an argument of the method. How can I call the checkHealth without passing in an argument that will overwrite the value value being injected?

private Health checkHealth(@Qualifier("myRestTemplate") RestTemplate restTemplate) {

}

@Bean(name = "myRestTemplate")
public RestTemplate myRestTemplate() {
    RestTemplateBuilder builder = new RestTemplateBuilder();
    return builder
        .rootUri(uri)
        .basicAuthentication("", "")
        .build();
}
Prashant :

Well you cannot! Note that Spring's annotations work in its Spring's context and not when you manually try to do something. What it means is that, the injection will effectively happen if and only if Spring invokes the method checkHealth() and not when you call this method. In your case, you do not need to pass in the argument. Simply call myRestTemplate() inside checkHealth() as:

private Health checkHealth() {
   final RestTemplate template = myRestTemplate();
   ...
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=169843&siteId=1