I have an application consuming REST, and I want to parameterize my API token into the RestTemplate
. I tried to autowire the bean containing the token, but the bean is still null at the time the RestTemplate
is created. I think I can do this using @PostConstruct
somehow, but I can't come up with the code. So I have this:
package com.company;
...
import com.company.api.dashboard.config.Credentials;
@SpringBootApplication
public class Main implements CommandLineRunner {
@Autowired
DashboardClient client;
@Autowired
Credentials credentials;
public static void main(String... args) throws Exception {
SpringApplication.run(Main.class, args);
}
@Bean
public RestTemplate restTemplateAS(RestTemplateBuilder builder) {
// here is where I try to use the autowired Credentials class
return builder.additionalInterceptors(new ASRequestHeaderInterceptor("Authorization", "Bearer " + credentials.getApiToken()),
new ASRequestHeaderInterceptor("ContentType", MediaType.APPLICATION_JSON.toString()),
new LoggingRequestInterceptor())
.messageConverters(new MappingJackson2HttpMessageConverter())
.requestFactory(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()))
.build();
}
...
}
And here is the Credentials
bean:
package com.company.api.dashboard.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties("credentials")
public class Credentials {
private String oauthUser;
private String oauthPassword;
private String apiToken;
public String getOauthUser() {
return oauthUser;
}
public void setOauthUser(String oauthUser) {
this.oauthUser = oauthUser;
}
public String getOauthPassword() {
return oauthPassword;
}
public void setOauthPassword(String oauthPassword) {
this.oauthPassword = oauthPassword;
}
public String getApiToken() {
return apiToken;
}
public void setApiToken(String apiToken) {
this.apiToken = apiToken;
}
}
If I can't autowire that apiToken
property, how else can I get it from my application.yml?