Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto generate client for Spring Controller

Tags:

java

spring

TL;DR: auto generate HTTP client for each REST Spring Controller to reuse in other services written with Spring.

When working with multiple micro-services that are written with spring I find myself rewriting the client for each controller. Lets say I write a controller in service X:

@RestController
public class SubscriptionController {

    @Autowired
    private SubscriptionService subscriptionService;

    @RequestMapping(value = "/subscription", method = RequestMethod.GET)
    public SubscriptionDTO getMySubscription() {
        return subscriptionService.getCurrentUserSubscription();
    }

}

I will import the DTO in service Y, write HTTP request to the mapping defined in the other service, and write tests for it.

@Service
public class SubscriptionApiService {

    @Autowired
    private HttpClient httpClinet;

    public SubscriptionDTO getMySubscription() {
        return httpClient.get("/subscription", SubscriptionDTO.class);
    }

}

It's very a repetitive process, and I'm quite sure someone already wrote a library to automate this process. However I was unable to find anything like that. Any idea?

like image 724
Kirill Kulakov Avatar asked Jan 23 '17 09:01

Kirill Kulakov


1 Answers

You can achieve this with Swagger2

@SpringBootApplication
@EnableSwagger2
public class Application extends SpringApplication {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

You can access Swagger2 html by this url: localhost:8080/swagger-ui.html

I also @ComponentScan my packages and these are the dependencies needed for Swagger2:

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.5.0</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.5.0</version>
    </dependency>
like image 73
Alexandru Hodis Avatar answered Oct 05 '22 05:10

Alexandru Hodis