SpringBoot之加载静态资源

文章目录

  • 默认静态资源路径及优先级
  • 自定义资源路径以及映射

默认静态资源路径及优先级

SpringBoot对于各组件的自动配置一般都是在spring-boot-autoconfigure包中,
重点查看一下两类文件:

  • ***AutoConfiguration
  • ***Properties

因此直接查看Web相关包,可以看到org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration有addResourceHandlers方法:

public void addResourceHandlers(ResourceHandlerRegistry registry) {
			//是否启动默认静态资源映射
			if (!this.resourceProperties.isAddMappings()) {
				logger.debug("Default resource handling disabled");
				return;
			}
			//资源文件缓存
			Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
			CacheControl cacheControl = this.resourceProperties.getCache()
					.getCachecontrol().toHttpCacheControl();
			// 如果容器中有的话,加载classpath下/webjars/**
			if (!registry.hasMappingForPattern("/webjars/**")) {
				customizeResourceHandlerRegistration(registry
						.addResourceHandler("/webjars/**")
						.addResourceLocations("classpath:/META-INF/resources/webjars/")
						.setCachePeriod(getSeconds(cachePeriod))
						.setCacheControl(cacheControl));
			}
			// 获取静态资源默认映射路径,默认为/**
			String staticPathPattern = this.mvcProperties.getStaticPathPattern();
			if (!registry.hasMappingForPattern(staticPathPattern)) {
				customizeResourceHandlerRegistration(
						// 加载默认静态资源
						registry.addResourceHandler(staticPathPattern)
								// 默认静态资源
								.addResourceLocations(getResourceLocations(
										this.resourceProperties.getStaticLocations()))
								.setCachePeriod(getSeconds(cachePeriod))
								.setCacheControl(cacheControl));
			}
		}

org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {

	private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
			"classpath:/META-INF/resources/", "classpath:/resources/",
			"classpath:/static/", "classpath:/public/" };

	/**
	 * Locations of static resources. Defaults to classpath:[/META-INF/resources/,
	 * /resources/, /static/, /public/].
	 */
	private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
//......
	//获取静态资源默认路径
	static String[] getResourceLocations(String[] staticLocations) {
			String[] locations = new String[staticLocations.length
					+ SERVLET_LOCATIONS.length];
			System.arraycopy(staticLocations, 0, locations, 0, staticLocations.length);
			System.arraycopy(SERVLET_LOCATIONS, 0, locations, staticLocations.length,
					SERVLET_LOCATIONS.length);
			return locations;
		}

由此可以知道SpringBoot中,默认静态资源的访问路径为:

  1. classpath:/META-INF/resources/
  2. classpath:/resources/
  3. classpath:/static/
  4. classpath:/public/

此默认路径优先级由高到低。

自定义资源路径以及映射

# 不会覆盖默认静态资源路径
spring:
  resources:
    static-locations: classpath:/mystatic/,classpath:/otherstatic/
# 只有在访问路径中有该路径时方可访问静态资源,如果设置了servlet-context,那么也需要在路径中加入。
  mvc:
    static-path-pattern: /mystatic

你可能感兴趣的:(SpringBoot)