//参照spring boot官方文档,编写自己的config类实现WebMvcConfigurer
If you want to keep Spring Boot MVC features, and you just want to add additional MVC configuration (interceptors, formatters, view controllers etc.) you can add your own @Configuration class of type WebMvcConfigurer, but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter or ExceptionHandlerExceptionResolver you can declare a WebMvcRegistrationsAdapter instance providing such components.If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.
//扩展springMVC的功能,既保留了所有的自动配置,也能用扩展配置
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//浏览器发送/lqh 请求会来到success
registry.addViewController("/lqh").setViewName("success");
}
}
@EnableWebMvc
全面接管springmvc,相当于之前写的springmvc的配置,完全去掉了自动配置
核心:失效原因,一步一步点进去看源码可以知道enable导入了DelegatingWebMvcConfiguration这个类,然后继承了WebMvcConfigurationSupport (这个类只实现了springmvc最基本的功能,拦截器,视图解析器需要自己配置),最后在WebMvcAutoConfiguration看到注解@ConditionalOnMissingBean
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
@Configuration(proxyBeanMethods = false)
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
@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() {
}
如何修改spring boot的默认配置**
springboot在自动配置很多组件时,先看容器有没有用户自己配置的 (@Bean,@Component),如果有的话会使用用户自己配置的,如果没有才自动配置;如果有些组件可以有多个(ViewResolver),将用户配置的和自动配置组合起来
看见xxxxConfigurer可以进行扩展配置
<link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/3.3.5/css/bootstrap.css}" rel="stylesheet">//使用th:href的好处:自动在加上properties的项目名
<link href="/restfulcrud/webjars/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
properties配置
server.servlet.context-path=/restfulcrud//访问:localhost:8081/restfulcrud/