提问者:小点点

Spring返回资源在纯JSON不是在HAL格式时,包括Spring数据Rest


当我为我的实体使用Spring Data Rest提供的默认控制器时,一切都像它应该的那样工作。输出如下所示:

{
  "_links" : {
    "search" : {
      "href" : "http://localhost:8080/users/search"
    }
  },
  "_embedded" : {
    "users" : [ {
      "firstName" : "Max",
      "lastName" : "Mustermann",
      "email" : "mail@max-mustermann.de",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/users/myadmin"
        }
      }
    } ]
  }
}

但是如果我使用自己的控制器,输出如下所示:

[ {
  "firstName" : "Max",
  "lastName" : "Mustermann",
  "email" : "mail@max-mustermann.de",
  "links" : [ {
    "rel" : "self",
    "href" : "http://localhost:8080/user/myadmin"
  } ]
} ]

我的控制器

@RestController
@RequestMapping("/user")
@EnableHypermediaSupport(type = {HypermediaType.HAL})
public class UserController {

    @Autowired
    UserRepository userRepository;

    @RequestMapping(method=RequestMethod.GET)
    public HttpEntity<List<User>> getUsers(){
        ArrayList<User> users = Lists.newArrayList(userRepository.findAll());
        for(User user : users){
            user.add(linkTo(methodOn(UserController.class).getUser(user.getUsername())).withSelfRel());
        }
        return new ResponseEntity<List<User>>(users, HttpStatus.OK);
    }

    @RequestMapping(value="/{username}", method= RequestMethod.GET)
    public HttpEntity<User> getUser(@PathVariable String username){
        User user = userRepository.findByUsername(username);
        user.add(linkTo(methodOn(UserController.class).getUser(user.getUsername())).withSelfRel());
        return new ResponseEntity<User>(user, HttpStatus.OK);
    }
}

我的用户:

@Entity
@Table(name="users")
public class User extends ResourceSupport{
    @Id
    private String username;

    private String firstName;
    private String lastName;

    @JsonIgnore
    private boolean enabled;

    @JsonIgnore
    private String password;

    @Column(unique =  true)
    private String email;

    public User(){
        enabled = false;
    }
    //Getters and Setters
}

如果我删除Spring data rest依赖项并包括spring-hateoas、spring-plugin-core和json-path(com. jayway.jsonpath),它可以工作…但我想对其他一些实体使用spring-data-rest

两个问题:

  1. 为什么不HAL默认值,包括Spring数据Rest?
  2. 如何将HAL设置为输出格式

共1个答案

匿名用户

您需要返回一个子类型的ResourceSupport(通常是ResourceResources)来启动HALJackson转换器。

此外,@EnableHypermediaSupport必须用于JavaConfig配置类,而不是控制器。