SprigBoot中的 WebMvcConfigurer与 WebMvcConfigurerAdapter和 WebMvcConfigurationSupport

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

猜你喜欢

转载自www.cnblogs.com/h-c-g/p/10849716.html