SpringBoot之扩展与全面接管SpringMVC
If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration
class of type WebMvcConfigurer
but without @EnableWebMvc
.
If you want to provide custom instances of RequestMappingHandlerMapping
, RequestMappingHandlerAdapter
, or ExceptionHandlerExceptionResolver
, and still keep the Spring Boot MVC customizations, you can declare a bean of type WebMvcRegistrations
and use it to provide custom instances of those components.
If you want to take complete control of Spring MVC, you can add your own @Configuration
annotated with @EnableWebMvc
, or alternatively add your own @Configuration
-annotated DelegatingWebMvcConfiguration
as described in the Javadoc of @EnableWebMvc
.
1.扩展springmvc
在springboot配置类中实现WebMvcConfigurer
接口
例如添加一个视图控制器
@Configuration
public class MySpringMVCConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/atguigu").setViewName("success");
}
}
2.全面接管springmvc
在实现WebMvcConfigurer
接口的配置类上加上@EnableWebMvc
注解
因为在Web Mvc 自动配置类中有
@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 {
在Web Mvc 自动配置类中@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
说明在IOC容器中没有WebMvcConfigurationSupport
类型的bean时, 自动配置才生效, 但是在@EnableWebMvc
注解中有
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({DelegatingWebMvcConfiguration.class}) //注意这里
public @interface EnableWebMvc {
}
在@EnableWebMvc
中导入了一个配置类DelegatingWebMvcConfiguration
, 而DelegatingWebMvcConfiguration
类是这样的
@Configuration(
proxyBeanMethods = false
)
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
也就是说@EnableWebMvc
注解向IOC容器中注入了一个WebMvcConfigurationSupport
类型的组件, 导致Web Mvc 自动配置类失效, 从而达到了全面接管springmvc