SpringBoot开发案例之配置静态资源文件路径

时间:2022-05-06
本文章向大家介绍SpringBoot开发案例之配置静态资源文件路径,主要内容包括前言、默认静态资源路径、新增静态资源路径、自定义静态资源映射、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

前言

SpringBoot本质上是为微服务而生的,以JAR的形式启动运行,但是有时候静态资源的访问是必不可少的,比如:image、js、css 等资源的访问。

默认静态资源路径

Spring Boot 对静态资源映射提供了默认配置,静态资源路径都是在classpath中:

classpath:/static
classpath:/public
classpath:/resources
classpath:/META-INF/resources

我们在src/main/resources目录下新建 public、resources、static 三个目录,并分别放入 1.jpg 2.jpg 3.jpg 三张图片。然后通过浏览器分别访问:

http://localhost:8080/1.jpg
http://localhost:8080/2.jpg
http://localhost:8080/3.jpg

地址均可以正常访问,Spring Boot 默认会从 public resources static 三个目录里面查找是否存在相应的资源。

新增静态资源路径

我们在spring.resources.static-locations后面追加一个配置classpath:/itstyle/:

# 静态文件请求匹配方式
spring.mvc.static-path-pattern=/**
# 修改默认的静态寻址资源目录 多个使用逗号分隔
spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/itstyle/

自定义静态资源映射

在实际开发中,我们可能需要自定义静态资源访问以及上传路径,特别是文件上传,不可能上传的运行的JAR服务中,那么可以通过继承WebMvcConfigurerAdapter来实现自定义路径映射。

application.properties 文件配置:

# 图片音频上传路径配置(win系统自行变更本地路径)
web.upload.path=/home/file/

WechatApplication.java 启动配置:

/**
 * 语音测评后台服务
 * 创建者 柒
 * 创建时间	2018年3月8日
 */
@SpringBootApplication
public class WechatApplication extends WebMvcConfigurerAdapter  {
	
	private final static Logger LOGGER = LoggerFactory.getLogger(WechatApplication.class);
	
	@Value("${web.upload.path}")
	private String uploadPath;
	
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		super.addResourceHandlers(registry);
		registry.addResourceHandler("/uploads/**").addResourceLocations(
				"file:"+uploadPath);
		LOGGER.info("自定义静态资源目录、此处功能用于文件映射");
	}
	
    public static void main(String[] args) {
        SpringApplication.run(WechatApplication.class);
        LOGGER.info("语音测评后台服务启动成功");
    }

}

我们可以访问以下路径:

http://localhost:8080/uploads/1.jpg