Reputation: 341
I have a REST controller. It processes the resource "messages". And each message can contain comments inside itself.
/api/v1/messages/1
/api/v1/messages/2
/api/v1/messages/1/comments/1
/api/v1/messages/1/comments/2
Here is a code:
@RestController
@RequestMapping("/api/v1/messages/")
public class RestControllerV1 {
@RequestMapping(value = "{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Message> getMessage(@PathVariable("id") Long messageId) {
}
@RequestMapping(value = "{messageId}/comments/{commentId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Comment> getComment(@PathVariable("messageId") Long messageId, @PathVariable("commentId") Long commentId) {
}
}
It works fine. But I think that it is not very good to have one big controller for two resources. So I want different controllers (SOLID, S-principle).
MessageControllerV1
and
CommentControllerV1
Is it possible to divide controllers in Spring Boot application?
Upvotes: 6
Views: 7996
Reputation: 130857
You could have something like:
@RestController
@RequestMapping("/api/v1/messages")
public class MessageController {
@RequestMapping(value = "{messageId}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Message> getMessage(@PathVariable("messageId") Long messageId) {
...
}
}
@RestController
@RequestMapping("/api/v1/messages/{messageId}/comments")
public class CommentController {
@RequestMapping(value = "{commentId}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Comment> getComment(@PathVariable("messageId") Long messageId,
@PathVariable("commentId") Long commentId) {
...
}
}
Upvotes: 14