spring boot攔截器WebMvcConfigurerAdapter,以及高版本的替換方案(轉)

文章轉自 http://blog.51cto.com/12066352/2093750java

最近項目採用spring icloud,用的spring boot版本是1.5.x的,spring boot 2.0,Spring 5.0 之後WebMvcConfigurerAdapter會取消掉。如下介紹下大致的內容,但願對你們都有所幫助。spring

  • 如下WebMvcConfigurerAdapter 比較經常使用的重寫接口

/** 解決跨域問題 **/ public void addCorsMappings(CorsRegistry registry) ; /** 添加攔截器 **/ void addInterceptors(InterceptorRegistry registry); /** 這裏配置視圖解析器 **/ void configureViewResolvers(ViewResolverRegistry registry); /** 配置內容裁決的一些選項 **/ void configureContentNegotiation(ContentNegotiationConfigurer configurer); /** 視圖跳轉控制器 **/ void addViewControllers(ViewControllerRegistry registry); /** 靜態資源處理 **/ void addResourceHandlers(ResourceHandlerRegistry registry); /** 默認靜態資源處理器 **/ void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer);
  • 新的版本解決方案目前有兩種

    方案1 直接實現WebMvcConfigurer跨域

    @Configuration public class WebMvcConfg implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/index").setViewName("index"); } }

    方案2 直接繼承WebMvcConfigurationSupportapp

    @Configuration public class WebMvcConfg extends WebMvcConfigurationSupport { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/index").setViewName("index"); } }

其實,源碼下WebMvcConfigurerAdapter是實現WebMvcConfigurer接口,因此直接實現WebMvcConfigurer接口也能夠;WebMvcConfigurationSupport與WebMvcConfigurerAdapter、接口WebMvcConfigurer處於同一個目錄下WebMvcConfigurationSupport包含WebMvcConfigurer裏面的方法,由此看來版本中應該是推薦使用WebMvcConfigurationSupport類的,WebMvcConfigurationSupport應該是新版本中對WebMvcConfigurerAdapter的替換和擴展【我的看法,若是有誤,請幫忙糾正】ide

相關文章
相關標籤/搜索