Spring-mvc主要通过WebMvcConfigurationSupport
类来实现对mvc的配置。
它有一个子类DelegatingWebMvcConfiguration
,类图如下:
1. 如何启用Spring-mvc配置呢?
只要在某一个@Configuration
类上加上@EnableWebMvc
就可以了,如下:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/**
* @author AlanSun
* @date 2019/5/20 17:58
**/
@EnableWebMvc
@Configuration
public class MyConfig {
...
}
注意:整个项目中只要有一个
@EnableWebMvc
注解就可以了。多个也不会报错(已测试)
2. 如何实现自定义的mvc配置呢?例如添加自定义转换器
- 想要实现mvc自定义配置其实也很简单,只要实现
WebMvcConfigurer
接口重写方法就可以,例如:
添加自定义转换器,具体实现请参考Spring中自定义类型转换器实现-基于JavaConfig配置
注意:你可以配置多个
WebMvcConfigurer
,Spring会整合这些所有的WebMvcConfigurer
。具体过程请看1.1
1.1 WebMvcConfigurer
的工作流程
这里必须要提到DelegatingWebMvcConfiguration
类,看下源码(一部分):
@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();
@Autowired(required = false)
public void setConfigurers(List<WebMvcConfigurer> configurers) {
if (!CollectionUtils.isEmpty(configurers)) {
this.configurers.addWebMvcConfigurers(configurers);
}
}
...other
}
首先可以看到DelegatingWebMvcConfiguration
使用@Configuration
注解,说明它是一个bean。setConfigurers
方法使用@Autowired(required = false)
注解,说明使用了依赖注入。最重要的来了,这里注入的依赖就是我们自定义的WebMvcConfigurer
实现,该方法接收的是个LIst<WebMvcConfigurer>
,说明我们可以自定义多个WebMvcConfigurer
实现。最后LIst<WebMvcConfigurer>
会被WebMvcConfigurerComposite
接收。后续操作都由WebMvcConfigurerComposite
来处理。
1.2 WebMvcConfigurerComposite
是什么
WebMvcConfigurerComposite
主要处理多个WebMvcConfigurer
。看源码可以清楚的看到,WebMvcConfigurerComposite
中的方法都是遍历WebMvcConfigurer
列表来处理的。
一般情况下实现WebMvcConfigurer
都能满足开发需要,但是如果想要使用高级功能,可以使用第二种方法。
- 继承
WebMvcConfigurationSupport
或DelegatingWebMvcConfiguration
重写方法。
SpringBoot中的mvc配置
传送门
网友评论