5

当我为我的实体使用由 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"
        }
      }
    } ]
  }
}

但是,如果我使用自己的 Controller,则输出如下所示:

[ {
  "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 数据的默认值?
  2. 如何将 HAL 设置为输出格式
4

1 回答 1

3

您需要返回ResourceSupport(通常是ResourceResources)的子类型以让 HAL Jackson 转换器启动。

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

于 2015-02-21T07:58:14.563 回答