1、开启mvc
注解方式下开启mvc的方式是添加@EnableMvc注解
@Configuration @EnableWebMvc public class AppConfig implements WebMvcConfigurer { }
查看@EnableMvc的源码会发现
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}
DelegatingWebMvcConfiguration是WebMvcConfigurationSupport的子类,它有一个方法setConfigurers
@Autowired(required = false) public void setConfigurers(List<WebMvcConfigurer> configurers) { if (!CollectionUtils.isEmpty(configurers)) { this.configurers.addWebMvcConfigurers(configurers); } }
它会加载所有WebMvcConfigurer接口的实现类,在代码方式去配置时,需要实现WebMvcConfigurer接口,通过重写接口中的方法,而实现自定义配置项。
使用XML方式是配置annotation-driven子标签
<mvc:annotation-driven/>
2、自定义配置
实现WebMvcConfigurer接口,重写其中的方法
@Configuration @EnableWebMvc public class AppConfig implements WebMvcConfigurer { }