Windows 11 21H2二、软件环境
Maven 3.8.1 jdk1.8.0_40 IntelliJ IDEA 2021.3.3 Spring Boot 2.6.7三、POM配置文件
四、Spring Boot 静态资源目录4.0.0 org.springframework.boot spring-boot-starter-parent 2.6.7 com.example demo 0.0.1-SNAPSHOT demo Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-maven-plugin org.projectlombok lombok
| 配置 | 资源目录 |
|---|---|
| /static | classpath:/static/ |
| /public | classpath:/public/ |
| /resources | classpath:/resources/ |
| /META-INF/resources | classpath:/META-INF/resources/* |
项目的打包类型分为:pom、jar、war
| 类型 | 作用 |
|---|---|
| pom | 父类型都为pom类型 |
| jar | 内部调用或者是作服务使用 |
| war | 需要部署的项目 |
POM是最简单的打包类型。不像一个JAR,SAR,或者EAR,它生成的构件只是它本身,没有代码需要测试或者编译,也没有资源需要处理,打包类型为POM的项目的默认目标。
| 生命周期阶段 | 目标 |
|---|---|
| package | site:attach-descriptor |
| install | install:install |
| deploy | deploy:deploy |
POM方式打包并没有将静态资源打包,所以无法访问静态资源
六、场景及解决方案 1、修改配置文件 (1)访问本地静态资源pom
适用场景:前后端未分离项目或需要访问项目内部html、js、img等静态资源。
spring:
mvc:
# 访问路径不需要加前缀 http://127.0.0.1:8080/1.jpg
static-path-pattern: /**
web:
# 资源目录,多个用逗号分隔
resources:
static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
(2)发布本地目录
适用场景:项目中有图片上传、在线浏览等场景,需要挂载并发布本地目录
spring:
mvc:
# 访问路径需要加前缀 http://127.0.0.1:8080/image/1.jpg
static-path-pattern: /image/**
web:
# 资源目录,多个用逗号分隔
resources:
static-locations: file:C:SoftWareWallpaper
2、实现WebMvcConfigurer
package com.example.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
@Configuration
class MyWebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 加载静态资源,访问路径不需要加前缀 http://127.0.0.1:8080/1.jpg
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/")
.addResourceLocations("classpath:/public/")
.addResourceLocations("classpath:/resources/")
.addResourceLocations("classpath:/META-INF/resources/");
// 挂在本地目录,访问路径需要加前缀 http://127.0.0.1:8080/image/1.jpg
registry.addResourceHandler("/image/**").addResourceLocations("file:C:/SoftWare/Wallpaper/");
WebMvcConfigurer.super.addResourceHandlers(registry);
}
}
参考文献:
- https://blog.csdn.net/qq_41094332/article/details/108497080
- https://blog.csdn.net/syc000666/article/details/105110117
- https://blog.csdn.net/xiaozheng12/article/details/100517099



