# 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/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/custom-static/", "file:/opt/static/");
}
}
@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();
}
@Autowired
private ServletContext servletContext;
public void getRealPath() {
String realPath = servletContext.getRealPath("/static/example.txt");
}
@Autowired
private Environment env;
public void getConfiguredPath() {
String staticLocations = env.getProperty("spring.web.resources.static-locations");
}
@Autowired
private ResourceHttpRequestHandler resourceHandler;
public void getResourceUrl() {
// 需要通過請求上下文獲取
}
@RequestMapping("/getUrl")
public String getResourceUrl(HttpServletRequest request) {
return ServletUriComponentsBuilder.fromRequest(request)
.replacePath("/static/example.jpg")
.toUriString();
}
getRealPath()
返回null,建議使用Resource.getInputStream()
file:
前綴指定絕對路徑spring.web.resources.cache.period=3600
spring.web.resources.cache.cachecontrol.max-age=1h
掌握SpringBoot靜態資源路徑的獲取和管理技巧,能夠幫助開發者更靈活地處理各種資源加載需求。根據實際場景選擇合適的方法,可以顯著提升應用的穩定性和可維護性。 “`
注:實際字數為約650字,如需擴展到850字,可以: 1. 增加更多代碼示例 2. 添加異常處理場景 3. 補充性能優化建議 4. 增加不同場景下的解決方案對比 5. 添加SpringBoot版本差異說明
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。