1. 程式人生 > >SprigBoot中的 WebMvcConfigurer與 WebMvcConfigurerAdapter和 WebMvcConfigurationSupport

SprigBoot中的 WebMvcConfigurer與 WebMvcConfigurerAdapter和 WebMvcConfigurationSupport

ces token condition oct print index 失效 gist ring

WebMvcConfigurationAdapter 過時?

在SpringBoot2.0之後的版本中WebMvcConfigurerAdapter過時了,所以我們一般采用的是如下的兩種的解決的方法。

(1)繼承WebMvcConfigureSupport

出現的問題:靜態資源的訪問的問題,在靜態資源的訪問的過程中,如果繼承了WebMvconfigureSupport的方法的時候,SpringBoot中的自動的配置會失效。 @ConditionalOnMissingBean({WebMvcConfigurationSupport.class}) 表示的是在WebMvcConfigurationSupport類被註冊的時候,SpringBoot的自動的配置會失效,就需要你自己進行配置 我自己的代碼

 @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //靜態資源的映射
        System.out.println("配置了");
        registry.addResourceHandler("/")
                .addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

配置完成之後就會成功,但是在自己配置攔截器的時候對於相應的資源的攔截也要自己配置,十分的麻煩,所以這種方法是不推薦的。

(2)推薦的方法(實現一個WebMvcConfigurer接口)

配置類如下:

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

    /**
     *配置攔截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
        .excludePathPatterns("/index","/","/user/login","/asserts/**","/webjars/**");
    }

//    @Override
//    public void addResourceHandlers(ResourceHandlerRegistry registry) {
//        //靜態資源的映射
//        System.out.println("配置了");
//        registry.addResourceHandler("/")
//                .addResourceLocations("classpath:/static/");
//        registry.addResourceHandler("/webjars/**")
//                .addResourceLocations("classpath:/META-INF/resources/webjars/");
//    }


    /**
     * 註意配置的方法的名字
     * @return
     */
    @Bean
    public MyLocaleResolver localeResolver() {
        return new MyLocaleResolver();
    }

}

不用自己去配置靜態資源的映射,配置攔截器的時候,只需要將自己的訪問的靜態的路徑不讓攔截器攔截即可

https://msd.misuland.com/pd/3107373619924174722

SprigBoot中的 WebMvcConfigurer與 WebMvcConfigurerAdapter和 WebMvcConfigurationSupport