当包含spring数据rest时,Spring以纯JSON而不是HAL格式返回Resource

时间:2015-02-20 22:55:51

标签: java json spring spring-data-rest hal-json

当我为我的实体使用默认控制器时,由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数据休息依赖项并包含spring-hateoas,spring-plugin-core和json-path(com.jayway.jsonpath)它可以正常运行..但是我想将spring-data-rest用于其他一些实体

两个问题:

  1. 为什么HAL不是包含弹簧数据的默认值?
  2. 如何将HAL设置为输出格式

1 个答案:

答案 0 :(得分:3)

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

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