当前位置: 代码迷 >> 综合 >> SpringBoot:接管和扩展SpringMVC配置
  详细解决方案

SpringBoot:接管和扩展SpringMVC配置

热度:17   发布时间:2023-09-18 16:07:04.0

1.扩展SpringMVC

1.1 xml方式添加组件,如拦截器,转换器等

<!--    配置拦截器--><mvc:interceptors><mvc:interceptor>
<!--         配置需要拦截的方法,通过访问的url来配置--><mvc:mapping path="/interceptor/*"/>
<!--        配置不拦截的方法    <mvc:exclude-mapping path=""/>--><!--        配置拦截器对象--><bean id="myInterceptor1" class="nju.software.utils.interceptor.MyInterceptor1"></bean></mvc:interceptor><mvc:interceptor><!--         配置需要拦截的方法,通过访问的url来配置/**表示拦截一切访问--><mvc:mapping path="/**"/><!--        配置不拦截的方法    <mvc:exclude-mapping path=""/>--><!--        配置拦截器对象--><bean id="myInterceptor2" class="nju.software.utils.interceptor.MyInterceptor2"></bean></mvc:interceptor></mvc:interceptors>

1.2 编写一个配置类

用@Configuration,它是一个WebMVCConfigurationAdapter类型;注意不能标注@EnableWebMvc。举例:

/*** 必须继承一个自动配置的适配器,* 这个适配器让我们避免了实现WebMvcConfigurer接口的麻烦*/
@Configuration//标注为配置类
public class MyMvcConfig extends WebMvcConfigurerAdapter {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {
//        super.addViewControllers(registry);//作用是发送liqiaoyu请求,就跳转到success页面,其路径由静态资源映射配置。//有时候,如果一些简单的跳转,不需要数据支持的,可以直接自定义一个视图控制器来解决registry.addViewController("/liqiaoyu").setViewName("success.html");}
}

注意我们继承的这个适配器,它是一个WebMvc配置接口的转接适配器,它的作用是避免我们去实现庞大的接口,只需要挑选我们需要的方法进行配置就好。上图我们选择的是一个视图配置器作为例子。

配置后,我们的扩展配置和SpringMVC的系统配置都会被SpringBoot全部读取到一个集成配置容器中,同时起作用。

2.@EnableWebMvc全面接管SpringMVC

SpringBoot不再需要SpringMVC的自动配置,而是全部都由我们自己配置。包括静态资源路径和自动配置的过滤器等。

我们只需要在配置类上添加@EnableWebMvc的标签即可。

@Configuration//标注为配置类
@EnableWebMvc//全面接管SpringMVC,一般不使用。
public class MyMvcConfig extends WebMvcConfigurerAdapter {
   

点进@EnableWebMvc标签:

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

再点击引入的DelegatingWebMvcConfiguration.class:

@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
   

再回头看看WebMvcAutoConfiguration的配置:

@Configuration
@ConditionalOnWebApplication(type = Type.SERVLET
)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
@AutoConfigureOrder(-2147483638)
@AutoConfigureAfter({DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class})
public class WebMvcAutoConfiguration {
   

@ConditionalOnMissingBean({WebMvcConfigurationSupport.class}),必须满足容器中没有WebMvcConfigurationSupport时自动配置才生效,而明显DelegatingWebMvcConfiguration正是WebMvcConfigurationSupport的只一个子类,所以当我们引入@EnableWebMvc的时候,它会引入一个WebMvcConfigurationSupport,就会使得SpringBoot的SpringMVC自动配置失效。只保留最基本的功能。

以后遇到xxxConfiguration的,都要意识到它的作用是SpringBoot的配置类,用于帮我们进行配置。

  相关解决方案