spring boot对springMvc的扩展

SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean、@Component)如果有就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默认的组合起来;
在SpringBoot中会有非常多的xxxConfigurer帮助我们进行方法扩展配置
在SpringBoot中会有很多的xxxCustomizer帮助我们进行属性定制配置

扩展springMVC编写一个配置类(@Configuration)并且实现 WebMvcConfigurer类

既保留了所有的自动配置,也能用我们扩展的配置;

 我这里用的2.x版本 springboot

1.x  继承WebMvcConfigurerAdapter

//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);
//浏览器发送 /atguigu 请求来到 success
registry.addViewController("/atguigu").setViewName("success");
}
}

2.x 实现WebMvcConfigurer 里面重写它的方法可以对页面跳转发出请求

@Configuration
//实现WebMvcConfigurer 是自己写配置配扩展springmvc的功能
public class MyConfig implements WebMvcConfigurer {

   //    @Override
//    public void addViewControllers(ViewControllerRegistry registry) {
    //浏览器发送/abc请求自动来到list页面
//       registry.addViewController("/abc").setViewName("list");
//    }
}

WebMvcConfigurer  是SpringMVC的自动配置类  在做其他自动配置时会导入

容器中所有的WebMvcConfigurer都会一起起作用; 我们的配置类也会被调用;

效果:SpringMVC的自动配置和我们的扩展配置都会起作用;

全面接管SpringMVC

如果说不需要springmvc的自动配置 在类上面加入@EnableWebMvc 不接管springmvc 这样springmvc自己的类就没用了

原理:

@EnableWebMvc的核心

@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class,
WebMvcConfigurerAdapter.class })
//容器中没有这个组件的时候,这个自动配置类才生效
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {

 @EnableWebMvc将WebMvcConfigurationSupport组件导入进来;

导入的WebMvcConfigurationSupport只是SpringMVC最基本的功能。

猜你喜欢

转载自blog.csdn.net/qq_43227109/article/details/88762064