0


重学SpringBoot3-WebMvcConfigurer接口

更多SpringBoot3内容请关注我的专栏:《SpringBoot3》
期待您的点赞👍收藏⭐评论✍

重学SpringBoot3-WebMvcConfigurer接口

上一篇文章对 SpringMVC 重要配置类——

WebMvcAutoConfiguration

类进行了介绍,下面介绍下它引入了几个重要组件之一

WebMvcConfigurer

接口。

WebMvcConfigurer基本信息

org.springframework.web.servlet.config.annotation.WebMvcConfigurer

WebMvcConfigurer

接口是 Spring MVC 提供的一个配置回调接口,允许自定义 Spring MVC 的各种配置而不需要继承特定的基类或使用 XML 配置文件。这个接口定义了一系列的方法,用于配置组件如视图解析器、消息转换器、拦截器、跨源请求处理、格式化程序以及其他各种设置。通过实现

WebMvcConfigurer

接口,可以在不改变应用程序现有工作流的情况下,扩展或修改 Spring MVC 的默认配置。

下面是一些

WebMvcConfigurer

接口中定义的方法及其用途的简介:

  1. addFormatters(FormatterRegistry registry): 用于添加自定义的格式化器和转换器。例如,你可以添加自定义的日期格式化器或字符串到枚举类型的转换器。
  2. addInterceptors(InterceptorRegistry registry): 允许注册拦截器,以实现在请求执行前后添加特定的功能,如权限检查、日志记录等。
  3. addResourceHandlers(ResourceHandlerRegistry registry): 用于配置静态资源的处理。可以指定静态资源的位置和缓存设置。
  4. addCorsMappings(CorsRegistry registry): 用于配置跨源请求处理。可以为不同的URL路径设置不同的跨源请求策略。
  5. addViewControllers(ViewControllerRegistry registry): 允许简单的自动控制器配置,可以用于将URL路径映射到视图而不需要一个实际的控制器。
  6. configureViewResolvers(ViewResolverRegistry registry): 用于配置视图解析器,可以自定义如何将视图名称解析为实际的视图。
  7. configureMessageConverters(List<HttpMessageConverter<?>> converters): 如前所述,这个方法用于添加或自定义消息转换器。
  8. addArgumentResolvers(List argumentResolvers): 用于添加自定义参数解析器,允许你自定义方法参数的解析规则。
  9. addReturnValueHandlers(List returnValueHandlers): 类似于参数解析器,但用于处理方法的返回值。
  10. configureContentNegotiation(ContentNegotiationConfigurer configurer): 用于配置内容协商的策略,决定请求的最佳响应格式。

实现

WebMvcConfigurer

接口的方法通常是通过创建一个配置类(标注有

@Configuration

注解)来完成的。在这个类中,你可以通过重写一个或多个方法来自定义 Spring MVC 的行为。这种方式的好处是你可以保持你的MVC配置集中在一个地方,并且可以非常精确地控制 Spring MVC 的行为,而不需要修改默认的配置或依赖XML文件。

为什么WebMvcConfigurer能配置底层行为

WebMvcConfigurer被调用

由上图可以看出:

  1. WebMvcAutoConfiguration 是一个 MVC 自动配置类,它里面有一个 EnableWebMvcConfiguration 类,EnableWebMvcConfiguration 继承自 DelegatingWebMvcConfiguration
  2. DelegatingWebMvcConfiguration 利用依赖注入把容器中所有 WebMvcConfigurer 注入进来;
  3. 当调用 DelegatingWebMvcConfiguration 的方法配置底层规则时,它会调用所有 WebMvcConfigurer 的配置底层方法。

实现WebMvcConfigurer举例

当然,下面是一些具体的使用

WebMvcConfigurer

接口进行 Spring MVC 自定义配置的例子。

1. 自定义格式化器和转换器

这个例子展示了如何添加自定义的日期格式化器到 Spring MVC 应用程序中。它可以将字符串自动转换成日期类型:

importorg.springframework.format.FormatterRegistry;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;importjava.time.LocalDate;importjava.time.format.DateTimeFormatter;@ConfigurationpublicclassWebConfigimplementsWebMvcConfigurer{@OverridepublicvoidaddFormatters(FormatterRegistry registry){
        registry.addFormatter(newDateFormatter());}privatestaticclassDateFormatterimplementsorg.springframework.format.Formatter<LocalDate>{@OverridepublicLocalDateparse(String text,Locale locale)throwsParseException{returnLocalDate.parse(text,DateTimeFormatter.ISO_DATE);}@OverridepublicStringprint(LocalDate object,Locale locale){returnDateTimeFormatter.ISO_DATE.format(object);}}}

2. 添加拦截器

这个例子展示了如何注册一个拦截器,它可以在请求处理之前和之后执行自定义逻辑:

importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.servlet.config.annotation.InterceptorRegistry;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;importmypackage.MyCustomInterceptor;@ConfigurationpublicclassWebConfigimplementsWebMvcConfigurer{@AutowiredprivateMyCustomInterceptor myCustomInterceptor;@OverridepublicvoidaddInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(myCustomInterceptor).addPathPatterns("/api/**");}}

在这个例子中,

MyCustomInterceptor

应该是实现了

HandlerInterceptor

接口的类。

3. 配置静态资源

这个例子展示了如何定义静态资源的位置以及如何设置缓存参数:

importorg.springframework.context.annotation.Configuration;importorg.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;@ConfigurationpublicclassWebConfigimplementsWebMvcConfigurer{@OverridepublicvoidaddResourceHandlers(ResourceHandlerRegistry registry){
        registry.addResourceHandler("/resources/**").addResourceLocations("/public-resources/").setCachePeriod(3600);}}
  • 如果有一个请求路径是/resources/images/myImage.png,Spring MVC 将会在 /public-resources/images/myImage.png 路径下查找该图片。
  • .setCachePeriod(3600): 这行代码为这些静态资源设置了HTTP缓存头的缓存期限,单位是秒。在这个例子中,它告诉浏览器或其他缓存服务,可以将这些资源缓存3600秒(即60分钟)。

4. 配置视图控制器

这个例子展示了如何将特定的URL路径映射到视图而不需要通过控制器处理:

importorg.springframework.context.annotation.Configuration;importorg.springframework.web.servlet.config.annotation.ViewControllerRegistry;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;@ConfigurationpublicclassWebConfigimplementsWebMvcConfigurer{@OverridepublicvoidaddViewControllers(ViewControllerRegistry registry){
        registry.addViewController("/home").setViewName("home");}}
  • addViewControllers(): 这是 WebMvcConfigurer 接口中的一个方法,用于注册视图控制器。ViewControllerRegistry是用来注册视图控制器的。
  • registry.addViewController("/home"): 这行代码注册了一个新的视图控制器。当请求路径为/home时,就会触发这个控制器。这种方式的好处是它不需要像典型的控制器那样编写一个完整的 Controller 类,尤其是当控制器仅仅是为了返回一个视图时。
  • .setViewName("home"): 这行代码指定当 /home 路径被访问时,应该返回的视图名称是 home。在 Spring MVC 中,视图名称用于解析实际的视图模板,这可能是一个 HTML 文件、JSP 页面等。具体解析到哪个视图文件取决于配置的视图解析器(ViewResolver)。例如,如果你使用 Thymeleaf 作为模板引擎,且你的视图文件存放在 src/main/resources/templates 目录下,那么 "home" 会被解析成 src/main/resources/templates/home.html

这些例子展示了

WebMvcConfigurer

接口的强大功能,可以用来自定义和配置 Spring MVC 的各个方面。通过实现该接口,你可以很容易地调整 Spring MVC 以满足你的应用程序需求。


本文转载自: https://blog.csdn.net/u014390502/article/details/136578253
版权归原作者 CoderJia_ 所有, 如有侵权,请联系我们删除。

“重学SpringBoot3-WebMvcConfigurer接口”的评论:

还没有评论