经过百度在此网址得到一些相关说明:https://www.jianshu.com/p/04b75f3108fd
SpringBoot项目配置HandlerInterceptorAdapter继承WebMvcConfigurationSupport导致自动化配置失效的解决方案
相关背景描述
Spring boot 版本:2.1.4.RELEASE
项目开发过程中需要简单校验一下session的有效性,相关用户权限信息。我决定使用Spring mvc 的 HandlerInterceptorAdapter 拦截器在Spring boot 1.X版本中我们只需配置WebMvcConfigurerAdapter即可,Spring boot 2.x 开始,使用Spring 组件的版本都是5.x,WebMvcConfigurerAdapter在Spring5中已经被遗弃,查询资料发现需要使用新的WebMvcConfigurationSupport。使用WebMvcConfigurationSupport新的问题就来了,Spring mvc的自动配置就失效了,静态资源无法正常访问。我在本项目中还想继续使用Spring mvc 的自动配置,找出了解决方案。
验证效果:【并未解决】
最终解决方式:
1、ZhxfInterceptor extends HandlerInterceptorAdapter 方法中
去除 @Autowired
private ZhxfConf zhxfConf;
加入 private String uaacType;
public ZhxfInterceptor(String uaacType){
this.uaacType = uaacType;
}
2、CustomMVCConfiguration extends WebMvcConfigurationSupport 方法中
加入 @Resource
private ZhxfConf zhxfConf;
new ZhxfInterceptor() 改为 new ZhxfInterceptor(zhxfConf.getUaacType())
部分示例:
@Configuration @ConfigurationProperties(prefix = "zhxf") public class ZhxfConf { private String uaacType; public String getUaacType() { return uaacType; } public void setUaacType(String uaacType) { this.uaacType = uaacType; } }
public class ZhxfInterceptor extends HandlerInterceptorAdapter { private static final Logger logger = LoggerFactory.getLogger(ZhxfInterceptor.class); private String uaacType; public ZhxfInterceptor(String uaacType){ this.uaacType = uaacType; } /** * 拦截处理 * @return true为拦截放行,会继续执行对应接口,false为拦截,不会进入接口api * @throws Exception */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if("1".equals(uaacType)) { String requestUrl = request.getRequestURI(); logger.info("请求path为: {}", request.getRequestURI()); } return true; }
}
(省略中间代码):
@Configuration public class CustomMVCConfiguration extends WebMvcConfigurationSupport { @Resource private ZhxfConf zhxfConf;
/** * 后台拦截,serverlet请求 **/ @Bean public ZhxfInterceptor getDemoInterceptor() { return new ZhxfInterceptor(zhxfConf.getUaacType()); }
/** * 前端拦截,静态资源 **/ @Bean public MappedInterceptor getMappedInterceptor() { return new MappedInterceptor(new String[] { "/static/html/**" }, new ZhxfInterceptor(zhxfConf.getUaacType())); }
}