spring boot 最佳实践(八)-- 请求上下文注入
开发Web API时除了用户请求参数以外,还有一些和请求状态相关的信息,比如登陆用户,购物车商品,user-agent,IP等。通常做法是采用HttpSession或request.attribute来存这些对象.然后从Controller拿到HttpRequest一层层的调用。但在无状态web服务中没有session信息,在service中操作request也不利于单元测试和接口解耦。
开发Web API时除了用户请求参数以外,还有一些和请求状态相关的信息,比如登陆用户,购物车商品,user-agent,IP等。通常做法是采用HttpSession或request.attribute来存这些对象.然后从Controller拿到HttpRequest一层层的调用。但在无状态web服务中没有session信息,在service中操作request也不利于单元测试和接口解耦。spring MVC为我们提供了自定义的方法参数注入接口,可以在需要的controller中为我们注入需要的请求上下文参数。
我们以登陆用户的注入为例演示实现方法。
如果我们使用spring security,登陆用户的信息被保存到http请求上下文中。所以我们需要实现WebArgumentResolver接口。
public class LoginUserArgumentResolver implements WebArgumentResolver {
@Override
public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) throws Exception {
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
if (methodParameter.getParameterType() == null || !methodParameter.getParameterType().equals(LoginUser.class)) {
return UNRESOLVED;
}
return request.getAttribute("loginUser");
}
}
我们需要在spring boot中配置这个参数处理类。
@Configuration
public class AppConfig implements WebMvcConfigurer {
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new ServletWebArgumentResolverAdapter(new LoginUserArgumentResolver()));
}
}
由于WebMvcConfigurer要求注入的接口是HandlerMethodArgumentResolver,所以需要ServletWebArgumentResolverAdapter做封装。如果我们不需要依赖http请求上下文可以直接实现HandlerMethodArgumentResolver接口。
然后我们就可以在controller中愉快的使用LoginUser了。
@RequestMapping(value = "/logout",method = RequestMethod.POST)
public void logout(LoginUser loginUser){
accountService.logout(loginUser);
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)