Sub-Resources in spring REST

java, request-mapping, rest, spring-boot, spring-mvc

Solution

In Spring boot, we can implement JAX-RS subresource concept using @Autowired Spring Concept. Create an object of your child resource class and Spring will initialize at runtime and return that object. Don't create an Object manually. like: Above mention scenario

 - MessageResource.java

@RestController
@RequestMapping("/messages")
public class MessageResource {

    MessageService messageService = new MessageService();
    @Autowired
    @Qualifier("comment")
    CommentResource comment;

    @RequestMapping(value = "/{messageId}/comments")
    public CommentResource getCommentResource() {
        return comment;
    }
}    

 - CommentResource.java

@RestController("comment")
@RequestMapping("/")
public class CommentResource {

    private CommentService commentService = new CommentService();

    @RequestMapping(method = RequestMethod.GET, value="/abc")
    public String test2() {
        return "this is test comment";
    }
}



Now it will work like sub-resource
http://localhost:8080/messages/1/comments/abc

You can send any type of request.

Problem

I'm trying to build messanger app. I've to call CommentResource from MessageResource. I want separate MessageResources and CommentResources. I'm doing something like this : MessageResource.java ``` @RestController @RequestMapping("/messages") public class MessageResource { MessageService messageService = new MessageService(); @RequestMapping(value = "/{messageId}/comments") public CommentResource getCommentResource() { return new CommentResource(); } } ``` CommentResource.java ``` @RestController @RequestMapping("/") public class CommentResource { private CommentService commentService = new CommentService(); @RequestMapping(method = RequestMethod.GET, value="/abc") public String test2() { return "this is test comment"; } } ``` I want http://localhost:8080/messages/1/comments/abc to return "this is test comment". Any Idea?? PS: In a simple word, I want to know `JAX-RS sub-resource` equivalent implementation in `spring-rest`

Original source