SpringBoot之扩展与全面接管SpringMVC

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值