背景web
在使用spring-boot進行的web開發中,會碰到須要爲Controller實現自定義的參數裝配,好比說咱們在Controller層中定義的方法:其中的TUserEntity每每是咱們從Request中根據token解析的,那本文介紹的就是如何實現參數正確匹配。spring
@RequestMapping("/hello") @ResponseBody public Object test(TUserEntity entity) { // to do return entity; }
TUserEntityapp
public classTUserEntity { private int id; private String name; // getter setter }
Application 入口ide
@SpringBootApplication @ComponentScan(basePackageClasses = Application.class) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args); } }
在spring boot中實現攔截器功能spring-boot
@Component public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { //實際狀況多是從request中得到token,繼而查找得到用戶實體 TUserEntity entity = new TUserEntity(); entity.setId(30); entity.setName("curry"); httpServletRequest.setAttribute("tUserEntity", entity); return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }
自定義參數解析器post
@Component public class MyArgumentResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter methodParameter) { return methodParameter.getParameterType().equals(TUserEntity.class); } @Override public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception { return nativeWebRequest.getAttribute("tUserEntity", 0); } }
以上基本就實現了功能,以後訪問http://localhost:8080/hello能夠獲得response:
{"id":30,"name":"curry"}
哈哈 我就是庫密code