Greg Zuber Greg Zuber - 3 years ago 205
Java Question

Spring: how to get rootUri from RestTempalte

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?

Answer Source

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 your restTemplate and inject this provider wherever you need either the endpointUrl or the restTemplate. 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download