Quantcast
Viewing all articles
Browse latest Browse all 4

Answer by Edd for How to Create or configure Rest Template using @Bean in Spring Boot

Judging form the name of the interceptor, I'm guessing you're doing some logging in it? You could of missed logging level configuration. I created a small application to check weather your configuration works, using 1.3.6.RELEASE version.

In this class I define the RestTemplate bean and the interceptor with logging.

package com.example;// imports...@SpringBootApplicationpublic class TestApplication {    private static final Logger LOGGER = LoggerFactory.getLogger(TestApplication.class);    public static void main(String[] args) {        SpringApplication.run(TestApplication.class, args);    }    @Bean(name = "appRestClient")    public RestTemplate getRestClient() {        RestTemplate restClient = new RestTemplate(                new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));        // Add one interceptor like in your example, except using anonymous class.        restClient.setInterceptors(Collections.singletonList((request, body, execution) -> {            LOGGER.debug("Intercepting...");            return execution.execute(request, body);        }));        return restClient;    }}

For logging to work, I also have to set the correct debug level in application.properties.

logging.level.com.example=DEBUG

Then I create a service where I inject this RestTemplate.

@Servicepublic class SomeService {    private final RestTemplate appRestClient;    @Autowired    public SomeService(@Qualifier("appRestClient") RestTemplate appRestClient) {        this.appRestClient = appRestClient;    }    public String callRestService() {        return appRestClient.getForObject("http://localhost:8080", String.class);    }}

And also an endpoint to test this out.

@RestControllerpublic class SomeController {    private final SomeService service;    @Autowired    public SomeController(SomeService service) {        this.service = service;    }    @RequestMapping(value = "/", method = RequestMethod.GET)    public String testEndpoint() {        return "hello!";    }    @RequestMapping(value = "/test", method = RequestMethod.GET)    public String test() {        return service.callRestService();    }}

By performing a GET request to http://localhost:8080/test I should expect to get the String hello! getting printed (the service makes a call to http://localhost:8080 which returns hello! and sends this back to me). The interceptor with logger also prints out Intercepting... in the console.


Viewing all articles
Browse latest Browse all 4

Trending Articles