传统SpringMVC集成自定义HandlerMethodArgumentResolver的方式为:http://www.cnblogs.com/yangzhilong/p/6282218.html
在SpringBoot中是去配置文件化的,具体做法有:
1、启动类继承WebMvcConfigurerAdapter
2、另外写一个@Configuration注解的来继承WebMvcConfigurerAdapter(推荐)
import java.util.List; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.longge.LoginUserInfoMethodArgumentResolver; @SpringBootApplication public class MyBootApplication extends WebMvcConfigurerAdapter{ public static void main(String[] args) { SpringApplication.run(MyBootApplication.class, args); } @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { super.addArgumentResolvers(argumentResolvers); argumentResolvers.add(new LoginUserInfoMethodArgumentResolver()); } }
import org.apache.commons.lang3.StringUtils; 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; import com.longge.utils.Constant; import com.longge.utils.RedisCacheUtils; /** * 获取用户的session dto */ public class LoginUserInfoMethodArgumentResolver implements HandlerMethodArgumentResolver { @Override public Object resolveArgument(MethodParameter arg0, ModelAndViewContainer arg1, NativeWebRequest arg2, WebDataBinderFactory arg3) throws Exception { String token = arg2.getHeader(Constant.TOKEN_KEY); if(StringUtils.isNotBlank(token)) { return RedisCacheUtils.getUserInfo(token); } return null; } @Override public boolean supportsParameter(MethodParameter arg0) { return arg0.getParameterType().equals(UserInfo.class); } }
使用方法:
@ApiOperation("新增") @PutMapping("add") public ResponseResult<SupplierDto> add(UserInfo userInfo, @Valid @RequestBody SupplierDto supplierDto) { // 这里的UserInfo不需要加任何注解,因为LoginUserInfoMethodArgumentResolver是对class的类型来解析的 }