我正在構建 SpringBoot 應用程式。
我喜歡為 SpringBoot 應用程式設定一個變數。此變數將在HTTP 攔截器中設定。我這樣做的原因是,這個變數將存盤一些 ID。并且此 ID 將在每個控制器的方法中使用。
你有什么想法我是怎么做到的?
uj5u.com熱心網友回復:
您在 HTTP 攔截器中設定變數?所以它不是一個唯一的全域變數,它是一個對每個請求都不同的 ID?這就是請求屬性的用途:
@Component
public class MyInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
if(request.getMethod().matches(RequestMethod.OPTIONS.name())) {
return true;
}
request.setAttribute("MY_ID", generateId(...));
return true;
}
}
@Controller
public class SampleController {
@RequestMapping(...)
public String something(HttpServletRequest req, HttpServletResponse res){
System.out.println( req.getAttribute("MY_ID"));
}
}
uj5u.com熱心網友回復:
- 將其作為 JVM 引數傳遞并使用 System.getProperty 使用它。
- 使用 -Dspring-boot.run.arguments=--interceptor.enabled=true 并在 application.properties 中保留備份配置或使用 -Drun.arguments 并直接在攔截器中訪問屬性鍵
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/450499.html
