【发布时间】:2016-08-18 16:58:39
【问题描述】:
我有一些 spring @RestControllers 方法,我想注入一个值,每个请求都作为请求属性(包含用户)附带一个值,例如:
@RestController
@RequestMapping("/api/jobs")
public class JobsController {
// Option 1 get user from request attribute as prop somehow
private String userId = "user1";
// Option 2 inject into method using aspect or something else
@RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Jobs>> getJobs() throws ResourceNotFoundException {
// currentUser is injected
this.getJobs(currentUser);
}
我知道我可以做到:
@RestController
@RequestMapping("/api/jobs")
public class JobsController {
@RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Jobs>> getJobs(HttpServletRequest request) throws ResourceNotFoundException {
String currentUser = null;
if (request.getAttribute("subject") != null) {
currentUser = request.getAttribute("subject").toString();
}
this.getJobs(currentUser);
}
但这需要我在程序中的每个方法中添加这段代码,在我看来,这是一种非常糟糕的做法。
有没有办法实现我想要的?
如果答案确实需要方面,将非常感谢代码示例,因为我只阅读过它,但实际上从未对方面做过任何事情。
更新
我建议的代码可以用这个来简化:
@RestController
@RequestMapping("/api/jobs")
public class JobsController {
@RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Jobs>> getJobs(@Value("#{request.getAttribute('subject')}" String currentUser) throws ResourceNotFoundException {
this.getJobs(currentUser);
}
但仍然需要我在每个方法中添加该参数。 这个参数可以以某种方式注入每个方法吗?
【问题讨论】:
-
你读过the reference guide吗?您不需要方面,因为它是开箱即用的......不要让事情变得比需要的更复杂。
-
我似乎无法理解它是如何开箱即用的?我需要将这段代码放在我拥有的每个方法上,我想避免它。
-
如果是 JWT 那么我强烈建议不要设置属性与请求正确集成并使用主体。这样,您可以在请求上执行
getPrincipal或简单地将Principal添加到方法签名中。如果您使用 Spring Security 解码 JWT,您将免费获得此支持(您需要配置)。