Issue
I'm using this configuration class to initialize RestTemplate:
@Configuration
public class RestTemplateConfig {
@Value("${endpoint-url}")
private String endpointUrl;
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder
.rootUri(endpointUrl)
.messageConverters(new MappingJackson2HttpMessageConverter())
.build();
}
}
And in one of my service's method I use the code:
RootUriTemplateHandler handler = (RootUriTemplateHandler) restTemplate.getUriTemplateHandler();
String uri = handler.getRootUri();
restTemplate.postForLocation(uri, request);
To get this URI. Is there an easier method to get this rootUri (without casting)? Or to execute the post request directly to rootUri?
Solution
Sounds like you are trying to use RestTemplate
to pass along the value of ${endpoint-url}
. That slightly awkward looking cast works but you could perhaps consider one of these alternatives:
Create a provider which encapsulates the
endpointUrl
and yourrestTemplate
and inject this provider wherever you need either theendpointUrl
or therestTemplate
. For example:@Component public class RestTemplateProvider { @Value("${endpoint-url}") private String endpointUrl; private final RestTemplate restTemplate; @Autowired public RestTemplateProvider(RestTemplateBuilder restTemplateBuilder) { this.restTemplate = restTemplateBuilder.rootUri(endpointUrl) .messageConverters(new MappingJackson2HttpMessageConverter()) .build(); } public RestTemplate provide() { return restTemplate; } public String getEndpointUrl() { return endpointUrl; } }
Inject
@Value("${endpoint-url}") private String endpointUrl;
into which ever service class needs it.
Answered By - glytching
Answer Checked By - Marilyn (JavaFixing Volunteer)