简体   繁体   中英

Spring boot - rest client from rest controller interface

With spring boot 2.6.0 (or above) is it possible to generate a rest client from aa controller interface?

Im wondering if its possible to build spring application like this following use case.

Spring application A needs to call spring application B rest interface

Spring application B is a multimodule project that produces server jar, and a api jar

Spring application A imports the B's API jar

Spring application A uses controller interface from B Api jar to make a rest client based on spring annotations.

B Api jar:


   @RestsController
   public interface MyApplicationAPI {

        @GetMapping("/api/some-endpoint)
        public SomeDto someEndpoint(SomeDTO obj);

   }

B server jar:

   public class BApplicationAPIImpl implements MyApplicationAPI {

        
        public SomeDto someEndpoint(SomeDTO obj) {
            return xxx;

And finally within A application:

      MyApplicationAPI restClient = Some.magic(MyApplicationAPI.class, "http://bappurl.com")
      SomeDto response = restClient.someEndpoint(param);

I believe that framework RestEasy supports similar approach, but you have to rely on JAXRS annotations.

Is there anything like that for spring framework? Or even better is there anything like this within spring already - i would prefer to rely on spring inhouse libraries and tools, rather than importing entire resteasy and jaxrs.

Spring Framework 6 (and Spring Boot 3) will have declarative HTTP interfaces ( see documentation ). However, they won't use the same annotations as controllers, but separate ones. So your example where you use the same interface for both controller and client won't be possible.

Code snippet from the documentation:

 interface RepositoryService { @GetExchange("/repos/{owner}/{repo}") Repository getRepository(@PathVariable String owner, @PathVariable String repo); // more HTTP exchange methods... }

Initialization (the Some.magic() part in your question) can be done with WebClient . As can be seen in the same documentation:

 WebClient client = WebClient.builder().baseUrl("https://api.github.com/").build(); HttpServiceProxyFactory factory = WebClientAdapter.createHttpServiceProxyFactory(client); factory.afterPropertiesSet(); RepositoryService service = factory.createClient(RepositoryService.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM