栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

WebMvcConfigurer接口配置讲解及@EnableWebMvc的坑

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

WebMvcConfigurer接口配置讲解及@EnableWebMvc的坑

一、@EnableWebMvc使用坑点解析

通过注解的方式来进行Spring4 MVC开发时,我们都会在配置文件中加入标签,这个配置会自动注册了一个 RequestMappingHandlerMapping、一个RequestMappingHandlerAdapter、以及一个ExceptionHandlerExceptionResolver 以支持使用注解Controller的注解方法(如@RequestMapping、@ExceptionHandler)来处理request,并开启一系列默认功能设置。




如果没有配置mvc:annotation-driven/,org.springframework.web.servlet.DispatcherServlet无法找到控制器并把请求分发到控制器。添加上后,请求会被相应的Controller处理。然而这时访问静态资源可能就不好使了,怎么办?一般可以使用 这个标签



所以这两个标签一般放在一起使用。

在Spring Boot中使用@EnableWebMvc也可能遇到类似的问题,@EnableWebMvc是使用注解方式快捷配置Spring Webmvc的一个注解。在使用时你可能会遇到以下问题:

  1. Spring Boot在application文件中的配置失效
  2. 在Spring Boot的自定义配置类加上@EnableWebMvc后,发现自动配置的静态资源路径(classpath:/META/resources/,classpath:/resources/,classpath:/static/,classpath:/public/)资源无法访问。

通过查看@EnableWebMvc的源码,可以发现该注解就是为了引入一个DelegatingWebMvcConfiguration 配置类,而DelegatingWebMvcConfiguration又继承于WebMvcConfigurationSupport。

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}

也就是说,如果我们使用@EnableWebMvc就相当于导入了WebMvcConfigurationSupport类,这个时候,Spring Boot的自动装配就不会发生了,我们能用的,只有WebMvcConfigurationSupport提供的若干个配置。其实不使用@EnableWebMvc注解也是可以实现配置Webmvc,只需要将配置类继承于WebMvcConfigurationSupport类即可。

  1. 当使用@EnableWebMvc时,加载的是WebMvcConfigurationSupport中的配置项。

  2. 当不使用@EnableWebMvc时,使用的是WebMvcAutoConfiguration引入的配置项。

查看一下WebMvcAutoConfiguration 的源码:

@Configuration
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
		ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {
	...
}

可以看到自动配置类 WebMvcAutoConfiguration 上有条件注解

@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)

这个注解的意思是在项目类路径中缺少 WebMvcConfigurationSupport类型的bean时改自动配置类才会生效。

有时候我们需要自己定制一些项目的设置,可以有以下几种使用方式:

  1. @EnableWebMvc + extends WebMvcConfigurationAdapter,在扩展的类中重写父类的方法即可,这种方式会屏蔽springboot的@EnableAutoConfiguration中的设置

  2. extends WebMvcConfigurationSupport,在扩展的类中重写父类的方法即可,这种方式会屏蔽springboot的@EnableAutoConfiguration中的设置

  3. extends WebMvcConfigurationAdapter/WebMvcConfigurer,在扩展的类中重写父类的方法即可,这种方式依旧使用springboot的@EnableAutoConfiguration中的设置

WebMvcConfigurer 没有暴露高级设置,如果需要高级设置 需要第二种方式继承WebMvcConfigurationSupport或者DelegatingWebMvcConfiguration,例如:

   @Configuration
   @ComponentScan(basePackageClasses = { MyConfiguration.class })
   public class MyConfiguration extends WebMvcConfigurationSupport {
   	   @Override
  	   public void addFormatters(FormatterRegistry formatterRegistry) {
           formatterRegistry.addConverter(new MyConverter());
  	   }
  	   @Bean
  	   public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
           // Create or delegate to "super" to create and
           // customize properties of RequestMappingHandlerAdapter
  	   }
   }

所以无论是使用@EnableWebMvc还是WebMvcConfigurationSupport,都会禁止Spring Boot的自动装配@EnableAutoConfiguration中的设置( 虽然禁止了Spring boot的自动装配,但是WebMvcConfigurationSupport本身,还是会注册一系列的MVC相关的bean的)。

@EnableAutoConfiguration是SpringBoot项目的启动类注解@SpringBootApplication的子元素,@EnableAutoConfiguration实际是导入EnableAutoConfigurationImportSelector和Registar两个类,主要功能是通过SpringFactoriesLoader.loadFactoryNames()导入jar下面配置文件META-INF/spring.factories。我们翻spring.factories,其中就包含WebMvc自动装配类:

...
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration,
...

并且@EnableAutoConfiguration 注解,会自动读取 application.properties 或 application.yml 文件中的配置。因此想想前面提到的第一个问题就很明白了。如果想要使用自动配置生效,同时又要使用部分spring mvc默认配置的话,比如增加 viewController ,则可以将自己的配置类可以继承 WebMvcConfigurerAdapter 这个类。不过在Spring5.0版本WebMvcConfigurerAdapter 后这个类被标记为@Deprecated了 。

可以看到WebMvcConfigurerAdapter也是实现了WebMvcConfigurer,本质上我们自己也可以通过实现该接口进行自定义。只不过Java8之后,接口有了默认方法,所以该类就可抛弃了

 * @author Rossen Stoyanchev
 * @since 3.1
 * @deprecated as of 5.0 {@link WebMvcConfigurer} has default methods (made
 * possible by a Java 8 baseline) and can be implemented directly without the
 * need for this adapter
 */
@Deprecated
public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {
	...
}

Spring 5.0后要使用Java8,而在Java8中接口是可以有default方法的,所以这个类就没必要了。所以我们只需要在自定义配置类中直接实现 WebMvcConfigurer 接口就好了

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyWebConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/hello").setViewName("helloworld");
    }
}

对于第二个问题,如果使用@EnableWebMvc了,那么就会自动覆盖了官方给出的/static, /public, META-INF/resources, /resources等存放静态资源的目录。而将静态资源定位于src/main/webapp。当需要重新定义好资源所在目录时,则需要主动添加上述的那个配置类,来重写 addResourceHandlers方法。

@Configuration
@EnableWebMvc
public class MyWebConfig implements WebMvcConfigurer {
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
	   registry.addResourceHandler("
default void addArgumentResolvers(List resolvers) {
}
  • 那么我们重写的这个方法是如何被Spring调用到的呢?

我们直接打开addArgumentResolvers方法的调用关系,发现被两个类调用,无论打开哪个类都可以找到最终调用的地方

我们打开DelegatingWebMvcConfiguration这个类,这个类是WebMvcConfigurer 的代理类,发现它的addArgumentResolvers方法是调用了成员变量configurers的addArgumentResolvers方法,查看这个成员变量,发现这个变量是通过@Autowired注解持有了所有自定义WebMvcConfigurer的子类。到了这里,我们看到了我们自定义的WebMvcConfigurer的子类是被DelegatingWebMvcConfiguration类通过注入的方法读取到的,由于使用的是@Autowired的方式,所以要求我们自定义的类需要使用@Configuration或者@Bean、或者@Component等注解,保证这个类被Spring容器管理才可以生效。

DelegatingWebMvcConfiguration的addArgumentResolvers方法

@Override
protected void addArgumentResolvers(List argumentResolvers) {
	this.configurers.addArgumentResolvers(argumentResolvers);
}

DelegatingWebMvcConfiguration中的configurers 成员变量,是通过@Autowired注解持有了所有自定义的WebMvcConfigurer的子类。

@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
	//这个成员变量是通过下面的@Autowired注解持有了所有自定义的WebMvcConfigurer的子类。
	private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();
    //关键逻辑:此处通过@Autowire注解实现了所有的自定义WebMvcConfigurer子类的注入,
	@Autowired(required = false)
	public void setConfigurers(List configurers) {
		if (!CollectionUtils.isEmpty(configurers)) {
			this.configurers.addWebMvcConfigurers(configurers);
		}
	}
  • 现在我们找到了Spring是如何读取自定义的WebMvcConfigurer 的子类的,那么Spring是在哪个地方使用的呢?

继续查看DelegatingWebMvcConfiguration 的addArgumentResolvers方法的调用链,我们发现是被WebMvcConfigurationSupport的addArgumentResolvers方法调用的,这个方法又被类内部的addDefaultHandlerExceptionResolvers方法和requestMappingHandlerAdapter方法调用,这两个方法分别是用来初始化SpringBoot的默认异常处理解析器ExceptionHandlerExceptionResolver和默认的请求映射处理适配器RequestMappingHandlerAdapter,分别打开两个方法,我们发现我们自定义的ArgumentResolvers被分别设置到了ExceptionHandlerExceptionResolver类和RequestMappingHandlerAdapter类中。

  • WebMvcConfigurationSupport的addDefaultHandlerExceptionResolvers方法
protected final void addDefaultHandlerExceptionResolvers(List exceptionResolvers) {
	ExceptionHandlerExceptionResolver exceptionHandlerResolver = createExceptionHandlerExceptionResolver();
	exceptionHandlerResolver.setContentNegotiationManager(mvcContentNegotiationManager());
	exceptionHandlerResolver.setMessageConverters(getMessageConverters());
	//设置自定义的参数解析器(通过重写WebMvcConfigurer的addArgumentResolvers方法)
	exceptionHandlerResolver.setCustomArgumentResolvers(getArgumentResolvers());
	exceptionHandlerResolver.setCustomReturnValueHandlers(getReturnValueHandlers())
  • WebMvcConfigurationSupport的requestMappingHandlerAdapter方法
@Bean
public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
    //创建一个默认配置的RequestMappingHandlerAdapter 
	RequestMappingHandlerAdapter adapter = createRequestMappingHandlerAdapter();
	adapter.setContentNegotiationManager(mvcContentNegotiationManager());
	adapter.setMessageConverters(getMessageConverters());
	adapter.setWebBindingInitializer(getConfigurableWebBindingInitializer());
	//设置自定义的参数解析器(通过重写WebMvcConfigurer的addArgumentResolvers方法)
	adapter.setCustomArgumentResolvers(getArgumentResolvers());
	adapter.setCustomReturnValueHandlers(getReturnValueHandlers());

至此,我们找到了WebMvcConfigurer子类重写的方法是如何被SpringBoot读取并且使用的,通过这个方式,可以分别找到WebMvcConfigurer类其它的方法的读取和使用的逻辑。后续Spring会在使用RequestMappingHandlerAdapter处理http请求或者使用ExceptionHandlerExceptionResolver 进行异常处理的时候,使用到我们自定义的ArgumentResolvers来进行参数的解析。

其他的方法调用流程举一反三:

  • 另外需要注意上面提到的:
  1. 实现了WebMvcConfigruer的自定义类,一定要加上@Configuration或者@Component注解,保证这个类被Spring容器管理才可以生效。
  2. 定制SpringMVC的配置要通过实现WebMvcConfigurer接口的方式,而不能继承WebMvcConfigruerSupport,因为一旦继承了WebMvcConfigruerSupport,会导致MVC的自动配置类WebMvcAutoConfiguration失效,产生不必要的问题。
@Configuration
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
//如果容器中存在WebMvcConfigurationSupport类型的Bean,则WebMvcAutoConfiguration类不生效
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
		TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {

可以看到,一旦容器中存在WebMvcConfigurationSupport类型的Bean,WebMvcAutoConfiguration类就不会生效。

  1. 部分方法详解
  • addInterceptors:拦截器
//addInterceptor:需要一个实现HandlerInterceptor接口的拦截器实例
public InterceptorRegistration addInterceptor(HandlerInterceptor interceptor) {
		InterceptorRegistration registration = new InterceptorRegistration(interceptor);
		this.registrations.add(registration);
		return registration;
	}
    • addPathPatterns:设置拦截器的过滤规则
public InterceptorRegistration addPathPatterns(String... patterns) {
   return addPathPatterns(Arrays.asList(patterns));
}
    • excludePathPatterns:用于设置不需要拦截的过滤规则
public InterceptorRegistration excludePathPatterns(String... patterns) {
   return excludePathPatterns(Arrays.asList(patterns));
}

拦截器主要用途:进行用户登录的拦截,访问日志(记录访客的ip,来源),在线统计人数,字符集转换,身份验证等

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new LoginHandlerInterceptor())
            .addPathPatterns("/**")
            .excludePathPatterns("/toAdminLoginPage","/","/toUserLoginPage")
            .excludePathPatterns("/adminLogin","/userLogin")
            .excludePathPatterns("/backstage/**","/commons/**","/forestage/**","/index/**","/login/**","/mine/**")
            .excludePathPatterns("/insertFeedback","/insertSubscribe");
}
  • addViewControllers:页面跳转

以前写SpringMVC的时候,如果需要访问一个页面,必须要写Controller类,然后再写一个方法跳转到页面,其实重写WebMvcConfigurer中的 addViewControllers() 方法即可达到效果了

@Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/toLogin").setViewName("login");
        registry.addViewController("/index.html").setViewName("index");
    }
  • addResourceHandlers:静态资源

比如,我们想自定义静态资源映射目录的话,只需重写 addResourceHandlers() 方法即可

    • addResoureHandler:对外暴露的访问路径
    • addResourceLocations:内部文件放置的路径
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/my/**").addResourceLocations("classpath:/my/");
    }
}
  • configureDefaultServletHandling:默认静态资源处理器
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
}
  • configureViewResolvers:视图解析器
    用来配置视图解析器的,该方法的参数 ViewResolverRegistry 是一个注册器,用来注册你想自定义的视图解析器等
@Bean
public InternalResourceViewResolver getMyViewResolver()
{
	InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
	//请求视图文件的前缀地址
	internalResourceViewResolver.setPrefix("/WEB-INF/jsp/");
	//请求视图文件的后缀
	internalResourceViewResolver.setSuffix(".jsp");
	return internalResourceViewResolver;
}

//视图配置
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
	super.configureViewResolvers(registry);
	registry.viewResolver(getMyViewResolver());
}
  • addCorsMappings:跨域

从4.2版本开始,Spring MVC支持CORS,在Spring Boot应用程序中使用带有@CrossOrigin批注的控制器方法CORS配置不需要任何特定的配置。可以通过使用自定义的addCorsMappings(CorsRegistry)方法注册WebMvcConfigurer bean来定义全局CORS配置,如以下示例所示:

@Configuration(proxyBeanMethods = false)
public class MyConfiguration {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**");
            }
        };
    }
}
  • 例子:
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")// 允许跨域访问的路径
            .allowedOrigins("*")// 允许跨域访问的源
            .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")// 允许请求方法
            .maxAge(168000)// 预检间隔时间
            .allowedHeaders("*")// 允许头部设置
            .allowCredentials(true);  // 是否发送cookie
}

但是interceptor和addCorsMappings一起的话addCorsMappings机会失效,应该是顺序问题,interceptor覆盖了

  • configureMessageConverters:信息转换器
 // 消息内容转换配置   配置fastJson返回json转换
@Override
public void configureMessageConverters(List> converters) {
    //创建fastJson消息转换器
    FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
    //创建配置类
    FastJsonConfig fastJsonConfig = new FastJsonConfig();
    //修改配置返回内容的过滤
    fastJsonConfig.setSerializerFeatures(
            SerializerFeature.DisableCircularReferenceDetect,
            SerializerFeature.WriteMapNullValue,
            SerializerFeature.WriteNullStringAsEmpty
    );
    fastConverter.setFastJsonConfig(fastJsonConfig);
    //将fastjson添加到视图消息转换器列表内
    converters.add(fastConverter);
}

参考文章
参考文章

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/944600.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号