Spring Boot 如何启用Web配置

前言

本文记录基于Spring Boot 2.0.4

一、Spring MVC启用Web配置

在Spring MVC中,提供了自定义Web的配置方式,通过继承WebMvcConfigurerAdapter,并使用@EnableWebMvc开启对Spring MVC的配置支持。例:

@Configuration
@EnableWebMvc
@ComponentScan("com.test")
public class MyWebMvcConfig extneds WebMvcConfigurerAdapter {
    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/classes/views");
        viewResolver.setSuffix(".jsp");
        viewResolver.setViewClass(JstlView.class);
        return viewResolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
            .addResourceLocations("classpath:/static")
            .addResourceLocations("classpath:/public")
            .addResourceLocations("classpath:/resources")
            .addResourceLocations("classpath:/META-INF/resources");
    }
}

上例中除了配置用于JSP的视图解析器InternalResourceViewResolver外,
还配置了项目中静态资源对外的访问路径,
比如将index.html文件放置于以下目录之一:

  • classpath:static/index.html
  • classpath:public/index.html
  • classpath:resources/index.html
  • classpath:META-INF/resources/index.html

当访问应用跟目录如localhost:8080/时会直接映射。

二、Spring Boot启用Web配置

在Spring Boot中,则提供了对于Web的自动配置,不必手动配置,
这在于Spring Boot运作时的WebMvcAutoConfiguration
回归到@SpringBootApplication,其中的核心是@EnableAutoConfiguration

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
    String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
    Class<?>[] exclude() default {};
    String[] excludeName() default {};
}

Spring Boot提供的Web自动配置有
1.ViewResolver配置,源码中如:

@Bean
@ConditionalOnMissingBean
public InternalResourceViewResolver defaultViewResolver() {
	InternalResourceViewResolver resolver = new InternalResourceViewResolver();
	resolver.setPrefix(this.mvcProperties.getView().getPrefix());
	resolver.setSuffix(this.mvcProperties.getView().getSuffix());
	return resolver;
}

2.静态资源对外路径配置,源码中如:

public void addResourceHandlers(ResourceHandlerRegistry registry) {
	if (!this.resourceProperties.isAddMappings()) {
        logger.debug("Default resource handling disabled");
    } else {
        Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
        CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
        if (!registry.hasMappingForPattern("/webjars/**")) {
            this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
        }
    
        String staticPathPattern = this.mvcProperties.getStaticPathPattern();
        if (!registry.hasMappingForPattern(staticPathPattern)) {
            this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
        }
    }
}

此后如果Spring Boot提供的Spring MVC默认配置不合需求,可以自定义配置MVC配置,通过前面的示例使用@Configuration@EnableWebMvc。这种方法是实现对MVC完全独立的控制(覆盖配置),Spring Boot提供的MVC自动配置均无效。
保留Spring Boot自动配置的情况下,并存自定义MVC配置。
在之前的Spring Boot版本中可以通过定义一个配置类(@Configuration)继承WebMvcConfigurerAdapter(不使用@EnableWebMvc),实现保留配置。
在Spring Boot 2.X版本中,自定义MVC配置则通过继承WebMvcConfigurerSupport或实现WebMvcConfigurer来实现,不再推荐WebMvcConfigurerAdapter
*继承WebMvcConfigurerSupport的配置方式是覆盖配置,
*实现WebMvcConfigurer的配置方式是保留配置。

在Spring Boot 2.X对MVC自动配置中,WebMvcAutoConfiguration源码如下

@Configuration
@ConditionalOnWebApplication(
type = Type.SERVLET
)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
@AutoConfigureOrder(-2147483638)
@AutoConfigureAfter({DispatcherServletAutoConfiguration.class, ValidationAutoConfiguration.class})
public class WebMvcAutoConfiguration {
//......
}

其中的注解@ConditionalOnMissingBean,限制了WebMvcAutoConfiguration在找不到WebMvcConfigurerSupport类型Bean时才生效,因此当存在自定义的WebMvcConfigurerSupport配置时,Spring Boot提供的自动配置不生效。


推荐文章

AI最佳实践全栈式从0到1开发个人博客系统

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我喺小VIE

努力创作,值得肯定●゜ⅴ゜)ノ

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值