简体   繁体   中英

Separating out REST API and implementation for Spring web services

I've been using Spring annotations such as @RestController and @RequestMapping to generate simple services in a Spring Boot Web application.

So I have this trivial example working correctly:

@RestController
public class HelloController {
    @RequestMapping("/")
    public String sayIt() {
        return "Hello!";
    }
}

Now, I would like to separate out an API library (jar) with only the REST interface and the DTOs. One or more separate libraries would provide the actual implementations of this interface. I can then use the (lightweight) API library on the client-side to generate REST client proxies to talk to any of the implementations.

So... are there any annotations or configuration to mark REST interfaces vs. implementations separately? If not, what is the Spring-y way to achieve this instead of using JAX-RS annotations?

@Something1
public class HelloServiceApi {
    @RequestMapping("/")
    public String sayIt();
}

@Something2
public class HelloServiceImpl implements HelloServiceApi {
    public String sayIt() {
        return "Hello!";
    }
}

I would advise to have a jar that contains the DTO objects only, without any logic. It then can be used by both the REST server and the client to transfer objects.

The client should not be dependent on the REST war/jar or the logic.

Furthermore, I would try to make sure my controller doesn't hold any logic aside from, maybe, transferring the DTOs into domain model objects which will then be passed to the business logic layer.

In my opinion, the REST layer should be only responsible for the external API, argument handling, sending to a layer bellow (service layer) and preparing a response.

That being said, you should have your different implementations at the service layer. This allows having the API/REST layer untouched and constant.

The service layer (being providing in different implementations) should respect some common interface that is later injected in the above rest layer.

Have I responded to your question?

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