1、WebMvcConfigurer 接口
需要实现什么功能,只要重写对于的方法即可
@Configuration@ComponentScan("com.sourceflag.spring.mvc")@EnableWebMvc // <mvc:annotation-driven/>public class AppConfig implements WebMvcConfigurer {/*** 视图处理*/@Overridepublic void configureViewResolvers(ViewResolverRegistry registry) {registry.jsp("/page/", ".html");}/*** 解析器添加*/@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();converters.add(fastJsonHttpMessageConverter);}}
2、WebMvcConfigurerAdapter 实现类(过时)
WebMvcConfigurerAdapter 其实就是实现了 WebMvcConfigurer 接口,是由于 JDK 1.8 以前接口是不可以有默认实现类的,所以出了一个 WebMvcConfigurerAdapter 类,所以现在已经过时了
@Deprecatedpublic abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {@Overridepublic void configurePathMatch(PathMatchConfigurer configurer) {}// ...}
3、WebMvcConfigurationSupport 实现类
这个类很特殊,实现了 ApplicationContextAware 和 ServletContextAware 接口, 提供了一些默认实现,同时提供了很多 @Bean 方法,但是并没有提供 @Configureation 注解,所以这些 @Bean 并不会生效,所以我们需要继承这个类,并在我们提供的类上提供 @Configureation 注解才能生效
public class WebMvcConfigurationSupport implements ApplicationContextAware, ServletContextAware {@Beanpublic PathMatcher mvcPathMatcher() {return getPathMatchConfigurer().getPathMatcherOrDefault();}// ...}
4、@EnableWebMvc 注解
@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)@Documented@Import(DelegatingWebMvcConfiguration.class)public @interface EnableWebMvc {}
通过 @Import 导入了 DelegatingWebMvcConfiguration.class 类
@Configuration(proxyBeanMethods = false)public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {}
这样我们就看的很清楚了,他直接继承了 WebMvcConfigurationSupport,同时也提供了 @Configuration 注解
使用
- 方式一:@EnableWebMvc + WebMvcConfigurer 接口的实现类
- 方式二:继承 WebMvcConfigurationSupport 类 + @Configuration 注解
- 方式三:WebMvcConfigurer 接口的实现类 + @Configuration 注解
