@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
// public interface ViewResolver 实现了视图解析器接口的类,我们就可以把它看做视图解析器 @Bean public ViewResolver MyViewResolver(){ return new MyViewResolver(); } //自定义了一个自己的视图解析器 public static class MyViewResolver implements ViewResolver{ @Override public View resolveViewName(String s, Locale locale) throws Exception { return null; } } }
设置视图跳转
package com.wang.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MyMvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("index"); registry.addViewController("/index.html").setViewName("index"); registry.addViewController("/main.html").setViewName("dashboard"); } @Bean public LocaleResolver localeResolver(){ return new MyLocalResolver(); } }
@EnableWebMvc这个注解添加时webMvc会被全面接管:因为WebMvcAutoConfiguration类上面有个条件注解
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)只有当没有WebMvcConfigurationSupport类是webmvc配置才会生效,但是加入了
@EnableWebMvc后会引入一个DelegatingWebMvcConfiguration类,这个类继承了WebMvcConfigurationSupport,也就是说webmvc配置不会生效