springboot實踐--springboot2.x中Interceptor使用
阿新 • • 發佈:2019-02-15
繼承WebMvcConfigurationSupport
的配置類
下面例子是引入第三方包中實現的攔截器,所以注入為bean先。若是使用已經注入為bean的攔截器,直接@Autowired或@Resource引入即可。
import org.springframework.beans.factory.annotation.Value; 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 InterceptorConf extends WebMvcConfigurationSupport { @Value("login.interceptor.enviroment.id") String enviromentId; /*@Value("login.interceptor.none.annotation.permission.level") String noneAnnotationPermissionLevel;*/ @Bean com.xxxx.xdcs.spring.interceptor.XdcsSpringMvcInterceptor xdcsSpringMvcInterceptor(){ return new XdcsSpringMvcInterceptor(); } @Bean com.xxxx.passport.sso.interceptor.LoginInterceptor loginInterceptor(){ LoginInterceptor loginInterceptor = new LoginInterceptor(); loginInterceptor.setEnvironmentId(enviromentId); loginInterceptor.setNoneAnnotationPermissionLevel(0); return loginInterceptor; } /** * 表示這些配置的是靜態檔案所處路徑, 不用攔截 */ public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**") .addResourceLocations("classpath:/static/"); registry.addResourceHandler("/templates/**") .addResourceLocations("classpath:/templates/"); super.addResourceHandlers(registry); } @Override public void addInterceptors(InterceptorRegistry registry) { // 自定義攔截器,新增攔截路徑和排除攔截路徑 registry.addInterceptor(xdcsSpringMvcInterceptor()).addPathPatterns("/**"); registry.addInterceptor(loginInterceptor()).addPathPatterns("/**").excludePathPatterns("/"); super.addInterceptors(registry); } }