需要我们对spring boot的自动配置原理非常熟悉,能够明白:
这些原理到哪里去找,要去:jar下的:
xxxxAutoConfiguration,帮我们在容器中配置相关组件;
xxxxProperties:配置类来封装配置文件的内容;
@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false) public class ResourceProperties implements ResourceLoaderAware, InitializingBean {
ResourceProperties :可以用来设置和静态资源有关的参数。比如说缓存时间;
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { if (!this.resourceProperties.isAddMappings()) { logger.debug("Default resource handling disabled"); return; } Integer cachePeriod = this.resourceProperties.getCachePeriod(); if (!registry.hasMappingForPattern("/webjars/**")) { customizeResourceHandlerRegistration(registry .addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/") .setCachePeriod(cachePeriod)); } String staticPathPattern = this.mvcProperties.getStaticPathPattern(); if (!registry.hasMappingForPattern(staticPathPattern)) { customizeResourceHandlerRegistration( registry.addResourceHandler(staticPathPattern) .addResourceLocations( this.resourceProperties.getStaticLocations()) .setCachePeriod(cachePeriod)); } }
-webjars:以 jar 包的方式引入静态资源;
-引入方式,可以通过 maven 的 pom.xml 文件引入 jar 包
<!--引入Juery-webjars--> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.4.1</version> </dependency>
-目录结构如下:
访问静态资源的时候,只需要写 webjars 下面资源的名称即可;例如访问 jquery.js,我们需要这样写:http://localhost:8083/webjars/jquery/3.4.1/jquery.js
1."classpath:/META-INF/resources/"
2. "classpath:/resources/"
3."classpath:/static/"
4. "classpath:/public/"
5."/":当前项目的根路径
即可以访问项目中以下位置的静态资源文件:
此时假如我们访问:localhost:8080/hai,就会去上面标注的静态资源文件夹里面去找
public Resource getWelcomePage() { for (String location : getStaticWelcomePageLocations()) { Resource resource = this.resourceLoader.getResource(location); try { if (resource.exists()) { resource.getURL(); return resource; } } catch (Exception ex) { // Ignore } } return null; }
此时我们输入 localhost:8083/ 后面不指定文件夹以及具体文件时,就会到以下五个文件夹中去寻找 Index.html 文件进行返回;
1."classpath:/META-INF/resources/" 2. "classpath:/resources/" 3."classpath:/static/" 4. "classpath:/public/" 5."/":当前项目的根路径
源码如下:
@Bean public SimpleUrlHandlerMapping faviconHandlerMapping() { SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1); mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", faviconRequestHandler())); return mapping; }
当然我们也可以不使用 spring boot 自身的静态资源文件夹,我可以自己配置静态资源文件夹的位置,配置方法如下:
spring.resources.static-locations=classpath:/hello/,classpath:/haibao/
可见无法访问;
此時就恢复了首页的访问,可见我们的修改的静态资源路径已经生效;
原文:https://www.cnblogs.com/haibaowang/p/11495808.html