Search code examples
spring-bootspring-restcontrollerspring-rest

how to split resource in spring boot


In Jersey we can do something like

@Path("/")
public class TopResource{
 
    @GET
    public Response getTop() { ... }
 
    @Path("content")
    public ContentResource getContentResource() {
        return new ContentResource();
    }

}
 
public class ContentResource {
 
    @GET
    public Response getContent() { ... }
}

so,

https://<host> will invoke getTop()

https://<host>/content will invoke getContent()

is there any equivalent in Spring?

I tried

@RestController
@RequestMapping("/")
public class TopResource{
 
    @GetMapping()
    public Response getTop() { ... }
 
    @RequestMapping("content")
    public ContentResource getContentResource() {
        return new ContentResource();
    }

}

@RestController
public class ContentResource {
 
    @GetMapping()
    public Response getContent() { ... }
}

only top resource works. content would return 404 Not Found. Not sure how to do this in Spring Boot. Tried replacing @RestController with @Resource and @Controller for content, but still got 404 Not Found.


Solution

  • There is no option to retun a whole class, please use the Annotation @RequestMapping on top of your content class to split them up.

    @RestController
    @RequestMapping("/")
    public class TopResource{
     
        @GetMapping()
        public Response getTop() { ... }
    
    }
    
    @RestController
    @RequestMapping("content")
    public class ContentResource {
     
        @GetMapping()
        public Response getContent() { ... }
    }