使用場景例子:html
用戶登錄系統通常會往Session裏放置一個VO對象,而後在controller裏會來獲取用戶的userId等信息。java
以前的寫法是:@SessionAttributes配合@ModelAttribute來進行參數值的注入,但這樣須要寫2個註解,其中SessionAttributes加在類上,ModelAttribute加在方法的屬性上。web
SpringMVC提供了HandlerMethodArgumentResolver接口來處理咱們的自定義參數的解析。spring
例子:session
一、獲取用戶信息的註解類mvc
import java.lang.annotation.*; /** * <p>綁定當前登陸的用戶</p> * <p>不一樣於@ModelAttribute</p> */ @Target({ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface CurrentUser { /** * 當前用戶在request中的名字 * * @return */ String value() default "loginUser"; }
二、自定義的參數解析器app
import com.gongren.cxht.pay.web.shiro.bind.annotation.CurrentUser; import org.springframework.core.MethodParameter; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.ModelAndViewContainer; /** * <p>自定義方法參數解析器 */ public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver { public CurrentUserMethodArgumentResolver() { } @Override public boolean supportsParameter(MethodParameter parameter) { if (parameter.hasParameterAnnotation(CurrentUser.class)) { return true; } return false; } @Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { CurrentUser currentUserAnnotation = parameter.getParameterAnnotation(CurrentUser.class); //從session的scope裏取CurrentUser註解裏的value屬性值的key的value return webRequest.getAttribute(currentUserAnnotation.value(), NativeWebRequest.SCOPE_SESSION); } }
三、將自定義的解析器加入springmvc的配置文件裏ide
<mvc:annotation-driven> <mvc:argument-resolvers> <!-- SESSION USER --> <bean class="com.test.CurrentUserMethodArgumentResolver"/> </mvc:argument-resolvers> </mvc:annotation-driven>
在controller裏的使用方法:spa
@RequestMapping(value = "/test") public String test(@CurrentUser AccUserVo user) { }
轉自 http://www.javashuo.com/article/p-feblgaeo-gh.html