sourcecode

리소스 및 컨트롤러 링크 작성기를 찾을 수 없으며 더 이상 사용되지 않습니다.

copyscript 2023. 7. 23. 14:37
반응형

리소스 및 컨트롤러 링크 작성기를 찾을 수 없으며 더 이상 사용되지 않습니다.

Spring Boot 2.2.0을 사용하고 있습니다.HATOAS와 Gradle이 있는 M1.

implementation 'org.springframework.boot:spring-boot-starter-hateoas'

지금 당장.ResourceIDE(IntelliJ IDEA 2018.3)에서 찾을 수 없습니다.ControllerLinkBuilder사용되지 않음으로 표시됩니다.

package com.example.restfulwebservicegradle.user;

import static org.springframework.hateoas.server.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;

import com.example.restfulwebservicegradle.User;
import com.example.restfulwebservicegradle.UserDaoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.server.mvc.ControllerLinkBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.validation.Valid;
import java.net.URI;
import java.util.List;

@RestController
public class UserResource {

    @Autowired
    private UserDaoService service;

    @GetMapping("users/{id}")
    public Resource<User> retrieveUser(@PathVariable int id) {
        User user = service.findOne(id);

        if (user == null)
            throw new UserNotFoundException("id-" + id);


        // Resource not found
        Resource<User> resource = new Resource<User>(user);

        // Deprecated
        ControllerLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllUsers());

        resource.add(linkTo.withRel("all-users"));

        return resource;
    }
}

IDE에 따라 사용할 수 있는 가져오기는 다음과 같습니다.

어떻게 해결해야 하나요?

내 목표는 찾는 것입니다.ResourceHATOAS로부터 그리고 대체품을 사용하는 것.ControllerLinkBuilder.

가장 근본적인 변화는 Spring HATOAS가 자원을 만들지 않는다는 사실입니다.이것이 바로 Spring MVC/Spring WebFlux의 기능입니다.우리는 하이퍼미디어의 공급업체 중립적인 표현을 만듭니다.그래서 이러한 핵심 유형의 이름을 변경했습니다.

링크 - https://spring.io/blog/2019/03/05/spring-hateoas-1-0-m1-released#overhaul

  1. 리소스 지원은 이제 표현 모델입니다.
  2. 리소스가 이제 엔티티 모델입니다.
  3. 리소스가 이제 수집 모델입니다.
  4. 페이징된 리소스가 이제 페이징된 모델입니다.

Resource로 대체됨EntityModel,그리고.ControllerLinkBuilder로 대체됨WebMvcLinkBuilder

다른 응답에 연결하는 중...다음 코드는 나에게 잘 작동했습니다...

UserResource.java

package com.---.---.restfulwebservices.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.validation.Valid;
import java.net.URI;
import java.util.List;

import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;

@RestController
public class UserResource {
    @Autowired
    private UserDaoService service;

    @GetMapping(path = "/users")
    public List<User> retrieveAllUsers() {
        return service.findAll();
    }

    @GetMapping(path = "/users/{id}")
    public EntityModel<User> retrieveUser(@PathVariable int id) {
        User user = service.findOne(id);
        if (null == user)
            throw new UserNotFoundException("id-" + id);

        EntityModel<User> entityModel = EntityModel.of(user);
        Link link= WebMvcLinkBuilder.linkTo(
                methodOn(this.getClass()).retrieveAllUsers()).withRel("all-users");
        entityModel.add(link);
        return entityModel;
    }

    @PostMapping(path = "/users")
    public ResponseEntity<Object> createUser(@Valid @RequestBody User user) {
        User newUser = service.saveUser(user);
        URI path = ServletUriComponentsBuilder.fromCurrentRequest()
                .path("/{id}").buildAndExpand(newUser.getId()).toUri();
        return ResponseEntity.created(path).build();
    }

    @DeleteMapping(path = "/users/{id}")
    public User deleteUser(@PathVariable int id) {
        User deletedUser = service.deleteUserByID(id);
        if (null == deletedUser)
            throw new UserNotFoundException("id-" + id);
        return deletedUser;
    }
}

pom.xml 종속성:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
UserResource controller = methodOn(UserResource.class);
    EntityModel<User> resource = EntityModel.of(user);

    Link link= WebMvcLinkBuilder.linkTo(controller
            .retriveAllUser()).withRel("all-users");

    resource.add(link);
    return resource;

여기서UserResourceis 컨트롤러retriveAllUser노출하려는 방법입니다.

패키지 구조의 가장 큰 변화는 Spring HATEOAS에서 추가 미디어 유형을 지원하기 위한 하이퍼미디어 유형 등록 API의 도입에 따른 것입니다.

https://docs.spring.io/spring-hateoas/docs/current/reference/html/

다른 동료 코더들이 언급한 바와 같이 HATEOAS에서 많은 변경(권장사항)이 발생하였으니 다음 코드를 사용하시기 바랍니다.

@RestController
public class UserResource {

    @Autowired
    private UserDaoService service;

    @GetMapping("users/{id}")
    public Resource<User> retrieveUser(@PathVariable int id) {
        User user = service.findOne(id);

        if (user == null)
            throw new UserNotFoundException("id-" + id);

        //Resource has been replaced by EntityModel
        EntityModel<User> resource = EntityModel.of(user);

        //ControllerLinkBuilder has been replace by WebMvcLinkBuilder
        Link link= WebMvcLinkBuilder.linkTo(methodOn(this.getClass()).retrieveAllUsers()).withRel("all-users");

        resource.add(link);
        return resource;
    }
}

그리고 이것은 봄-혐오 의존성입니다, 당신은 이것을 추가해야 합니다.pom.xml:

<dependency>
    <groupId>org.springframework.hateoas</groupId>
    <artifactId>spring-hateoas</artifactId>
    <version>1.1.0.RELEASE</version>
</dependency>

1.0으로의 spring-hateoas 마이그레이션 스크립트에서 이전 클래스 및 해당하는 새 클래스를 찾을 수 있습니다.

https://github.com/spring-projects/spring-hateoas/blob/main/etc/migrate-to-1.0.sh

ex:

 ControllerLinkBuilder -> hateoas.server.mvc.WebMvcLinkBuilder

언급URL : https://stackoverflow.com/questions/55770163/resource-and-controllerlinkbuilder-not-found-and-deprecated

반응형