引入拦截器及swagger支持及解决redis无法初始化问题
Springboot引入拦截器
自定义的拦截器类 Interceptor
package cn.zytao.taosir.auth.config; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class AuthInterceptor implements HandlerInterceptor{ /** * 请求处理之后 */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // TODO Auto-generated method stub HandlerInterceptor.super.afterCompletion(request, response, handler, ex); } /** * 请求处理之后调用 */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // TODO Auto-generated method stub HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); } /** * 请求处理之前 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return HandlerInterceptor.super.preHandle(request, response, handler); } }
将拦截器添加到springmvc配置中,并放行swagger的相关资源
package cn.zytao.taosir.auth.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; @Configuration public class SpringMVCConfig extends WebMvcConfigurationSupport{ @Bean public AuthInterceptor getAuthInterceptor() { return new AuthInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry) { registry .addInterceptor(getAuthInterceptor()) .addPathPatterns("/**") .excludePathPatterns("/login") .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**"); super.addInterceptors(registry); } @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); super.addResourceHandlers(registry); } }
在addInterceptors方法中添加拦截器时,是new的一个拦截器。而并不是引入springBean容器初始化时,已经初始化好了的bean实例,并不是同一个对象,故而访问时肯定是无法引入Interceptor类里面引入的bean实例,可能产生空指针异常。即无法引入默认注入的Bean,那么我们就自己定义一个Bean,然后在拦截器添加方法内引入这个bean即可,上面主要对此进行了处理。
作者:涛先森の日常
出处:https://www.cnblogs.com/it-taosir/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。