1、springMVC使用xml配置文件
//增加视图控制器
<mvc:view-controller path="/hello" view-name="success"/>
//增加拦截器
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/hello"/>
<bean></bean>
</mvc:interceptor>
</mvc:interceptors>
2、springboot扩展springMVC
springboot在保留springMVC默认配置的情况下,还允许我们扩展springMVC。新版本的springboot扩展springMVC需要我们手写一个javaConfig配置类实现WebMvcConfigure接口。重点强调配置类上不能加上@EnableWebMvc注解,否则会使默认配置失效,导致这个配置类会全面接管springMVC的配置。
@Configuration
//@EnableWebMvc 标注了这个注解,这个配置类会全面接管springMVC的配置
public class MyWebMvcConfigure implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/wust").setViewName("index.html");//跳转到首页
}
//所有的WebMvcConfigurer组件都会一起起作用
@Bean
public WebMvcConfigurer webMvcConfigurer(){
return new WebMvcConfigurer() {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/test").setViewName("index.html");//跳转到首页
}
};
}
}
3、@EnableWebMvc的原理
- EnableWebMvc.java
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({DelegatingWebMvcConfiguration.class})
public @interface EnableWebMvc {
}
在使用该注解时发现会导入一个DelegatingWebMvcConfiguration的组件,查看DelegatingWebMvcConfiguration.java时,发现其继承了WebMvcConfigurationSupport这个类
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();
public DelegatingWebMvcConfiguration() {
}
...............................................................
}
- 最后再回到WebMvcAutoConfiguration这个自动配置类上
@Configuration(
proxyBeanMethods = false
)
@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 {
public static final String DEFAULT_PREFIX = "";
public static final String DEFAULT_SUFFIX = "";
private static final String[] SERVLET_LOCATIONS = new String[]{"/"};
public WebMvcAutoConfiguration() {
}
...............................................................
}
发现springMVC的自动配置类上拥有这样一个注解:@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})。意思是当容器中存在WebMvcConfigurationSupport这种组件时,会使配置类失效。这就是标注了@EnableWebMvc,会使springboot中springMVC的默认配置失效的原因。