我有一些彈簧@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);
}
但仍需要我在每一個方法添加參數。 該參數可以以某種方式注入每種方法嗎?
你讀過[參考指南](http://docs.spring.io/彈簧/文檔/電流/彈簧的框架參考/ HTML/mvc.html#MVC-ANN-requestheader)?你不需要一個方面,因爲它支持開箱即用......不要讓事情變得更復雜,然後需要。 –
我似乎無法理解它是如何開箱即用的?我需要把這段代碼放在每一種方法上,我想避免它。 – Osher
如果是JWT,那麼我強烈建議不要設置屬性與請求正確集成並使用委託人。這樣你可以在請求上執行'getPrincipal'或者簡單地將'Principal'添加到方法簽名中。如果你使用Spring Security解碼JWT,你可以免費獲得這種支持(以及你需要的配置)。 –