在不结合SpringBoot时 要配置SpringMVC时 须写配置文件来配置路径转发和拦截器之类的组件
例如:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:view-controller path="/hello" view-name="success"/>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/hello"/>
<bean></bean>
</mvc:interceptor>
</mvc:interceptors>
</beans>
那么SpringBoot中没有配置文件 该如何实现上述功能?
其实 只需编写一个配置类(用@Configuration
注解标注)
该类的类型为WebMvcConfigurerAdapter 且不能标注@EnableWebMvc注解
扩展SpringMVC
扩展的意思就是 既保留了所有的自动配置 也能使用自己扩展的配置
需要创建自定义的配置类
例:
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// 设置视图映射规则
// 当浏览器发送/gotosuccess请求 跳转到success页面(页面也是由模板引擎的视图解析器来解析的)
registry.addViewController("/gotosuccess").setViewName("success");
}
}
这样 需要视图映射的时候 就无须用Controller来帮助跳转了
原理:
继承的WebMvcAutoConfiguration是SpringMVC在SpringBoot中对应的的自动配置类
该类有个@Import(EnableWebMvcConfiguration.class)
注解
即 该类在做其他自动配置时会导入名为EnableWebMvcConfiguration的类
该类的父类里面 会自动装配 从容器中获取所有的WebMvcConfigurer
然后将WebMvcConfigurer相关配置都调用一遍
这样 容器中所有的WebMvcConfigurer都会一起起作用
如此 SpringMVC的自动配置和自己写的的扩展配置都会起作用
全面接管SpringMVC
若要完全掌控SpringMVC 只需要添加@EnableWebMvc
这一个注解
放弃SpringBoot对SpringMVC的自动配置 全部自己配置
所有的SpringMVC的自动配置全部失效
例:
@EnableWebMvc
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
...
}
}
原理:
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
...
}
@EnableWebMvc
注解底层导入了一个名为DelegatingWebMvcConfiguration的类
@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
...
}
而 在自动配置类中 添加了一个@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
注解
意即 当容器中没有WebMvcConfigurationSupport组件时 该自动配置类才生效
但DelegatingWebMvcConfiguration继承了WebMvcConfigurationSupport
因此自动配置类就失效了
又由于 导入的WebMvcConfigurationSupport只有SpringMVC最基本的功能 因此 全部的组件都需要自己配置