I am building SpringBoot Application.
I like to set a variable for the SpringBoot application. this variable will be set in an HTTP interceptor. The reason I do this, this variable will store some ID. and This ID will be used in methods in every controller.
Do you have any Idea How I achieve this?
CodePudding user response:
You SET the variable in an HTTP interceptor? So it's not a unique global variable, it's an ID that is different for every request? That's what request attributes are for:
@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"));
}
}
CodePudding user response:
- Pass it as JVM args and use it using System.getProperty.
- Use -Dspring-boot.run.arguments=--interceptor.enabled=true and keep a backup config in application.properties or using -Drun.arguments and access the property key directly in your interceptor