programing

스프링 REST의 하위 리소스

stoneblock 2023. 7. 18. 21:30

스프링 REST의 하위 리소스

메신저 앱을 만들려고 합니다.

MessageResource에서 CommentResource를 호출해야 합니다.

저는 별도의 메시지 리소스와 댓글 리소스를 원합니다.

저는 다음과 같은 일을 하고 있습니다.

MessageResource.java

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

    MessageService messageService = new MessageService();

    @RequestMapping(value = "/{messageId}/comments")
    public CommentResource getCommentResource() {
        return new 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";
    }
}

나는 되고 싶다.

http://localhost:8080/http/1/http/http/http

"이것은 테스트 주석입니다"를 반환합니다.

아이디어 있어요?

PS: 간단히 말해서, 저는 알고 싶습니다.JAX-RS sub-resource에 있어서의 동등한 실행.spring-rest

Spring boot에서는 @AutoWired Spring Concept를 사용하여 JAX-RS 하위 리소스 개념을 구현할 수 있습니다.하위 리소스 클래스의 개체를 만들면 실행 시 Spring이 초기화되고 해당 개체를 반환합니다.개체를 수동으로 만들지 마십시오.좋아요: 위에 언급된 시나리오

 - 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.

URL(http://localhost:8080/messages/1/comments/abc)은 주석이 메시지에 중첩되어 있음을 나타냅니다.컨트롤러의 모양은 다음과 같습니다.

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

    @RequestMapping(value = "/{messageId}")
    public String getCommentResource(@PathVariable("messageId") String messageId) {
        //test
        return messageId;
    }

    @RequestMapping(value = "/{messageId}/comments/{commentsContent}")
    public String getCommentResource(
                      @PathVariable("messageId") String messageId, 
                      @PathVariable("commentsContent") String commentsContent) {
        //test
        return messageId + "/" + commentsContent;
    }
}

MessageResource 클래스에서 무엇을 하고 싶은지 완전히 확신할 수는 없지만, 아이디어는 거기에 있습니다.

나머지 - HTTP 메서드

현재 이러한 용도는 Get requests입니다.그러나 적절한 Http 방법을 사용하는 것이 좋습니다.

  • 가져오기: 리소스 읽기
  • 게시물: 리소스 생성
  • Put: 업데이트
  • 삭제 : 삭제 :)

http://www.restapitutorial.com/lessons/httpmethods.html 에서 확인할 수 있습니다.

게시물의 예:

@RequestMapping(method=RequestMethod.POST, value = "/{messageId}/comments/{commentsContent}")
    public ResponseEntity<String> getCommentResource(
                                  @PathVariable("messageId") String messageId, 
                                  @RequestBody Comment comment) {
        //fetch the message associated with messageId
        //add the comment to the message
        //return success
        return new ResponseEntity<String>(HttpStatus.OK);
 }

클래스 이름

또한, 개인적으로 이 클래스의 이름을 MessageController 및 CommentController로 변경합니다.

주석 뒤에 편집 - 컨트롤러 분할

컨트롤러를 문자 그대로 분할할 수 있습니다(기존 컨트롤러에 더 가깝습니다).

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

    @RequestMapping(value = "/{messageId}")
    public String getCommentResource(@PathVariable("messageId") String messageId) {
        //test
        return messageId;
    }
}

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

    @RequestMapping(value = "/{messageId}/comments/{commentsContent}")
    public String getCommentResource(
                      @PathVariable("messageId") String messageId, 
                      @PathVariable("commentsContent") String commentsContent) {
        //test
        return messageId + "/" + commentsContent;
    }
}

찾고 있는 항목은 에서 지원됩니다.JAX-RSJersey와 같은 구현 및 호출됨Sub-Resources자연스럽게 중첩되는 대규모 API를 구축할 때 하위 리소스는 매우 유용한 기능입니다.

Spring Boot 기본 Rest 구현은JAX-RS그렇지만SpringMVCSpring Boot에서 Jersey를 사용하는 것은 가능하지만, Jersey를 설정하는 데 약간 관여하고 있으며, 커뮤니티에서 잘 사용/지원되지 않는 것으로 보입니다.

참고로, DropWizard는 정말 멋집니다!

저도 JAX-RS에서 Spring-MVC로 강제 이주당했습니다.

저는 여전히 JAX-RS와 마찬가지로 우아한 방법을 찾고 있습니다.

제가 노력한 것을 공유합니다.

@RestController
@RequestMapping("parents")
public class ParentsController {

    @RequestMapping(method = RequestMethod.GET,
                    produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<List<Parent>> read() {
    }

    @RequestMapping(method = RequestMethod.GET,
                    path = "/{id:\\d+}",
                    produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<Parent> read(@PathVariable("id") final long id) {
    }
}

그리고.ChildrenController.

@RestController
@RequestMapping("/parents/{parentId:\\d+}/children")
public class ChildrenController {

    @RequestMapping(method = RequestMethod.GET,
                    produces = {MediaType.APPLICATION_JSON_VALUE})
    @ResponseBody
    public List<Child> read(@PathVariable("parentId") final long parentId) {
    }

    @RequestMapping(method = RequestMethod.GET, path = "/{id:\\d+}",
                    produces = {MediaType.APPLICATION_JSON_VALUE})
    @ResponseBody
    public Child read(@PathVariable("parentId") final long parentId,
                     @PathVariable("id") final long id) {
    }
}

내가 찾은 두 가지 문제는

@PathVariable필드에는 해당되지 않습니다.

할 수 없어요.@PathVariable("parentId") private long parentId;

에 대한 다중 에 대한 ChildrenController

은 JAX-RS를 매핑할 수 입니다.ChildrenController심지어 그와 같은 다른 길들을 위하여.ChildrenController클래스 레벨이 있습니다.@Path그것과 함께.

@Path("/children");
public class ChildrenResource {
}

@Path("/parents")
public class ParentsResource {

    @Path("/{id}/children")
    public ChildrenResource resourceChildren() {
    }
}


/children
/parents/{id}/children

단순하게 하시면 됩니다.두 개의 클래스를 만들고 상수를 사용하여 하위 리소스를 상위 리소스와 함께 참조합니다.이를 통해 두 클래스 간의 연결을 만들고 개발자가 두 클래스 간의 관계를 이해할 수 있습니다.

그래서:

@RequestMapping(value= MessageController.URL)
public class MessageController {
    public static final String URL= "/messages";
}

그리고:

@RequestMapping(value = MessageController.URL + "/{idMessage}/comments")
public class CommentController {

}

컨트롤러를 다른 패키지로 분할하여 패키지 조직에서도 이 계층을 표시할 수 있습니다.

com.company.web.message.MessageController
com.company.web.message.comment.CommentController 

MessagesController.java

@RestController
@RequestMapping(value = "/messages")
public class MessageController {

    @Autowired
    private MessagesService messageService;

}

CommentController.java

@RestController
@RequestMapping("/messages/{messageId}/comments")
public class CommentController {


    @GetMapping
    public List<Comment> getComments(@PathVariable("messageId") Long messageId) {
        System.out.println("Get "+messageId);

        return null;
    }

}

MessageResource.java

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

    MessageService messageService = new MessageService();

    // as usual messages related CRUD operations
}

주석 리소스.java

@RestController
@RequestMapping("messages/{messageId}/comments")
public class CommentResource {

    private CommentService commentService = new CommentService();

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

언급URL : https://stackoverflow.com/questions/40328835/sub-resources-in-spring-rest