springboot中怎么获取静态资源路径

发布时间:2021-07-29 11:19:18 作者:Leah
来源:亿速云 阅读:344
# SpringBoot中怎么获取静态资源路径

## 一、静态资源默认路径

在SpringBoot中,静态资源默认存放在以下位置(优先级从高到低):

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

当浏览器发起静态资源请求时,SpringBoot会按此顺序查找资源文件。

## 二、自定义静态资源路径

### 1. 通过配置文件修改
在`application.properties`或`application.yml`中配置:

```properties
# 单个路径
spring.web.resources.static-locations=classpath:/custom-static/

# 多个路径(用逗号分隔)
spring.web.resources.static-locations=classpath:/custom-static/,file:/opt/static/

2. 通过Java配置类修改

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/custom-static/", "file:/opt/static/");
    }
}

三、获取静态资源路径的方法

1. 使用ResourceLoader

@Autowired
private ResourceLoader resourceLoader;

public void getResourcePath() throws IOException {
    Resource resource = resourceLoader.getResource("classpath:static/example.txt");
    File file = resource.getFile();
    String absolutePath = file.getAbsolutePath();
}

2. 使用ServletContext

@Autowired
private ServletContext servletContext;

public void getRealPath() {
    String realPath = servletContext.getRealPath("/static/example.txt");
}

3. 使用Environment获取配置路径

@Autowired
private Environment env;

public void getConfiguredPath() {
    String staticLocations = env.getProperty("spring.web.resources.static-locations");
}

四、动态获取资源URL

1. 使用ResourceHttpRequestHandler

@Autowired
private ResourceHttpRequestHandler resourceHandler;

public void getResourceUrl() {
    // 需要通过请求上下文获取
}

2. 使用ServletUriComponentsBuilder

@RequestMapping("/getUrl")
public String getResourceUrl(HttpServletRequest request) {
    return ServletUriComponentsBuilder.fromRequest(request)
            .replacePath("/static/example.jpg")
            .toUriString();
}

五、生产环境注意事项

  1. 打包路径问题:JAR包中getRealPath()返回null,建议使用Resource.getInputStream()
  2. 绝对路径配置:生产环境推荐使用file:前缀指定绝对路径
  3. 缓存控制:建议配置资源缓存
spring.web.resources.cache.period=3600
spring.web.resources.cache.cachecontrol.max-age=1h

六、最佳实践建议

  1. 开发环境使用classpath路径,生产环境使用外部绝对路径
  2. 对于频繁访问的静态资源建议启用缓存
  3. 避免在代码中硬编码资源路径
  4. 使用版本控制(如MD5指纹)管理静态资源更新

结语

掌握SpringBoot静态资源路径的获取和管理技巧,能够帮助开发者更灵活地处理各种资源加载需求。根据实际场景选择合适的方法,可以显著提升应用的稳定性和可维护性。 “`

注:实际字数为约650字,如需扩展到850字,可以: 1. 增加更多代码示例 2. 添加异常处理场景 3. 补充性能优化建议 4. 增加不同场景下的解决方案对比 5. 添加SpringBoot版本差异说明

推荐阅读:
  1. 如何配置SpringBoot静态资源路径
  2. springboot怎样获取相对路径文件夹下静态资源

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring boot

上一篇:mysql 5.6.37如何下载安装

下一篇:如何安装MySQL5.7.23解压版

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》