我的项目正在从自定义json格式转移到json-hal和spring-data-rest。为了继续支持“旧” json,我想与新的Spring-Data- Rest提供的并行运行现有的Resource-Controller。
每当我将spring-data-rest配置为使用与我们现有控制器相同的URL时,仅使用旧控制器,并且如果accept- header不匹配,我将收到错误响应。当我使用其他网址时,一切正常
是否可以将控制器与弹簧数据支架并行运行,并根据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 { ... } }
@RepositoryRestController``@RequestMapping在类型级别上玩不好。第一步,通过produces从RequestMapping中删除参数来确保您确实设法捕获了请求(我在这里使用GetMapping快捷方式)。我还删除了@PreAuthorize注释,因为它目前不相关,并引入了一个参数来捕获Accept标头值(用于调试):
@RepositoryRestController``@RequestMapping
produces
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 ,并且仍然可以从Spring Data Rest自动提供的 POST / PUT / PATCH … / api / accounts中 受益,并断言content-type
如果它按预期工作,则可以:
produces = "application/custom.account+json"
那给你:
@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 { ... } }
现在: