我的项目正在从自定义的json格式转移到json-hal和spring-data-rest。继续支持“旧”json我希望运行现有的资源控制器并行提供新的Spring-Data-Rest。
每当我将spring-data-rest配置为使用与现有控制器相同的url时,只使用旧控制器,如果accept-header不匹配,则会收到错误响应。当我使用不同的网址时,一切正常
是否可以与spring-data-rest one并行运行一个控制器并根据Accept-Header进行响应?
旧控制器:
@RepositoryRestController
@RequestMapping(value = "/api/accounts", produces = {"application/custom.account+json"})
public class AccountResource {
@RequestMapping(method = RequestMethod.GET)
@PreAuthorize("#oauth2.hasScope('read') and hasRole('ROLE_ADMIN')")
public ResponseEntity<List<Account>> getAll(
@RequestParam(value = "page", required = false) Integer offset,
@RequestParam(value = "per_page", required = false) Integer limit,
@RequestParam(value = "email", required = false) String email
) throws URISyntaxException {
...
}
}
答案 0 :(得分:2)
@RepositoryRestController
与type level @RequestMapping
的效果不佳。
第一步,通过从RequestMapping中删除produces
参数(我在此处使用GetMapping快捷方式),确保实际设法捕获请求。我还删除了@PreAuthorize注释,因为它现在不相关,并引入了一个参数来捕获Accept
标头值(用于调试):
@RepositoryRestController
public class AccountResource {
@GetMapping(value = "/api/accounts")
public ResponseEntity<List<Account>> getAll(
@RequestParam(value = "page", required = false) Integer offset,
@RequestParam(value = "per_page", required = false) Integer limit,
@RequestParam(value = "email", required = false) String email,
) throws URISyntaxException {
...
}
}
有了这个,您应该可以随意自定义 GET / api / accounts 并仍然可以从 POST / PUT / PATCH ... / api / accounts 中受益由Spring Data Rest自动提供,并断言内容类型
如果按预期工作,您可以:
produces = "application/custom.account+json"
缩小方法范围(单个值不需要大括号),并查看端点和Spring生成的端点方法是否可用这会给你:
@RepositoryRestController // NO MAPPING AT THE TYPE LEVEL
public class AccountResource {
@GetMapping(value = "/api/accounts", // Mapping AT THE METHOD LEVEL
produces = "application/custom.account+json") // the content-type this method answers to
@PreAuthorize("#oauth2.hasScope('read') and hasRole('ADMIN')") // ROLE is 'ADMIN' not 'ROLE_ADMIN'
public ResponseEntity<List<Account>> getAll(
@RequestHeader("Content-Type") String contentType,
@RequestParam(value = "page", required = false) Integer offset,
@RequestParam(value = "per_page", required = false) Integer limit,
@RequestParam(value = "email", required = false) String email,
) throws URISyntaxException {
...
}
}
现在: