[spring6: Resource ResourceLoader ResourceEditor]-加載資源

Resource

Resource 接口為處理和訪問不同類型資源(如文件、URL、輸入流等)提供了統一的 API,支持資源的存在性檢查、讀取、轉換等操作。

public interface Resource extends InputStreamSource {boolean exists();default boolean isReadable() {return exists();}default boolean isOpen() {return false;}default boolean isFile() {return false;}URL getURL() throws IOException;URI getURI() throws IOException;File getFile() throws IOException;default ReadableByteChannel readableChannel() throws IOException {return Channels.newChannel(getInputStream());}default byte[] getContentAsByteArray() throws IOException {return FileCopyUtils.copyToByteArray(getInputStream());}default String getContentAsString(Charset charset) throws IOException {return FileCopyUtils.copyToString(new InputStreamReader(getInputStream(), charset));}long contentLength() throws IOException;long lastModified() throws IOException;Resource createRelative(String relativePath) throws IOException;@NullableString getFilename();String getDescription();}
public interface InputStreamSource {InputStream getInputStream() throws IOException;
}
實現類描述
UrlResource用于封裝 java.net.URL,可以訪問任何通過 URL 訪問的資源,如文件、HTTPS、FTP 等。
ClassPathResource用于從類路徑加載資源,支持使用類加載器或特定類來加載資源。
FileSystemResource基于 java.io.File 的實現,支持文件系統路徑,采用 Java NIO API 進行操作。
PathResource基于 java.nio.file.Path 的實現,采用 NIO API,支持文件和 URL 解析,且實現了 WritableResource 接口。
ServletContextResource用于 ServletContext 資源,解析相對路徑并在 Web 應用的根目錄下查找資源。
InputStreamResource封裝已打開的 InputStream,適用于流式訪問已打開的資源,避免多次讀取。
ByteArrayResource基于給定字節數組的實現,通過 ByteArrayInputStream 來加載內容,適合加載內存中的數據。

ResourceLoader

ResourceLoader 接口用于資源加載策略,通常在 Spring 應用中用于加載文件、類路徑或其他類型的資源。它的子接口和實現類則為其功能擴展,支持不同類型的應用上下文或資源解析需求。|

public interface ResourceLoader {/** Pseudo URL prefix for loading from the class path: "classpath:". */String CLASSPATH_URL_PREFIX = ResourceUtils.CLASSPATH_URL_PREFIX;Resource getResource(String location);@NullableClassLoader getClassLoader();}

DefaultResourceLoader

DefaultResourceLoader 是 Spring 中用于加載各種類型資源的默認實現,支持通過類路徑、文件系統、URL 等方式加載,并允許擴展協議解析器。

// Direct Known Subclasses:
// AbstractApplicationContext, ClassRelativeResourceLoader, FileSystemResourceLoader, ServletContextResourceLoader
public class DefaultResourceLoader implements ResourceLoader {@Nullableprivate ClassLoader classLoader;private final Set<ProtocolResolver> protocolResolvers = new LinkedHashSet<>(4);private final Map<Class<?>, Map<Resource, ?>> resourceCaches = new ConcurrentHashMap<>(4);public DefaultResourceLoader() {}public DefaultResourceLoader(@Nullable ClassLoader classLoader) {this.classLoader = classLoader;}public void addProtocolResolver(ProtocolResolver resolver) {Assert.notNull(resolver, "ProtocolResolver must not be null");this.protocolResolvers.add(resolver);}@SuppressWarnings("unchecked")public <T> Map<Resource, T> getResourceCache(Class<T> valueType) {return (Map<Resource, T>) this.resourceCaches.computeIfAbsent(valueType, key -> new ConcurrentHashMap<>());}public void clearResourceCaches() {this.resourceCaches.clear();}@Overridepublic Resource getResource(String location) {Assert.notNull(location, "Location must not be null");for (ProtocolResolver protocolResolver : getProtocolResolvers()) {Resource resource = protocolResolver.resolve(location, this);if (resource != null) {return resource;}}if (location.startsWith("/")) {return getResourceByPath(location);}else if (location.startsWith(CLASSPATH_URL_PREFIX)) {return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());}else {try {// Try to parse the location as a URL...URL url = ResourceUtils.toURL(location);return (ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));}catch (MalformedURLException ex) {// No URL -> resolve as resource path.return getResourceByPath(location);}}}protected Resource getResourceByPath(String path) {return new ClassPathContextResource(path, getClassLoader());}protected static class ClassPathContextResource extends ClassPathResource implements ContextResource {public ClassPathContextResource(String path, @Nullable ClassLoader classLoader) {super(path, classLoader);}@Overridepublic String getPathWithinContext() {return getPath();}@Overridepublic Resource createRelative(String relativePath) {String pathToUse = StringUtils.applyRelativePath(getPath(), relativePath);return new ClassPathContextResource(pathToUse, getClassLoader());}}
}

ResourcePatternResolver

ResourcePatternResolverResourceLoader 的擴展接口,提供了通過模式(如 Ant 風格路徑)解析位置并返回 Resource 對象的功能。它支持 classpath*: 前綴來獲取類路徑和模塊路徑中所有匹配的資源。

// "classpath:META-INF/config.xml" 只匹配 第一個 META-INF/config.xml
// "classpath*:META-INF/config.xml" 匹配 所有 JAR 包 和 所有 META-INF 目錄 下的 config.xml// PathMatchingResourcePatternResolver
public interface ResourcePatternResolver extends ResourceLoader {String CLASSPATH_ALL_URL_PREFIX = "classpath*:";Resource[] getResources(String locationPattern) throws IOException;}

ResourceEditor

ResourceEditor 通過繼承 PropertyEditorSupport 提供了對資源路徑的自動解析和加載功能。它能夠將字符串路徑轉換為 Resource 類型,同時支持占位符解析和動態路徑處理。這使得資源的配置和加載變得更加靈活與便捷,尤其適用于需要根據配置或環境動態加載資源的場景。

public class ResourceEditor extends PropertyEditorSupport {private final ResourceLoader resourceLoader;@Nullableprivate PropertyResolver propertyResolver;private final boolean ignoreUnresolvablePlaceholders;public ResourceEditor() {this(new DefaultResourceLoader(), null);}public ResourceEditor(ResourceLoader resourceLoader, @Nullable PropertyResolver propertyResolver) {this(resourceLoader, propertyResolver, true);}public ResourceEditor(ResourceLoader resourceLoader, @Nullable PropertyResolver propertyResolver,boolean ignoreUnresolvablePlaceholders) {Assert.notNull(resourceLoader, "ResourceLoader must not be null");this.resourceLoader = resourceLoader;this.propertyResolver = propertyResolver;this.ignoreUnresolvablePlaceholders = ignoreUnresolvablePlaceholders;}@Overridepublic void setAsText(String text) {if (StringUtils.hasText(text)) {String locationToUse = resolvePath(text).trim();setValue(this.resourceLoader.getResource(locationToUse));}else {setValue(null);}}protected String resolvePath(String path) {if (this.propertyResolver == null) {this.propertyResolver = new StandardEnvironment();}return (this.ignoreUnresolvablePlaceholders ? this.propertyResolver.resolvePlaceholders(path) :this.propertyResolver.resolveRequiredPlaceholders(path));}@Override@Nullablepublic String getAsText() {Resource value = (Resource) getValue();try {return (value != null ? value.getURL().toExternalForm() : "");}catch (IOException ex) {return null;}}}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/89022.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/89022.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/89022.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Spring Boot - Spring Boot 集成 MyBatis 分頁實現 PageHelper

一、PageHelper 概述 PageHelper 是一個優秀的 MyBatis 分頁插件&#xff0c;可以方便地在 Spring Boot 項目中使用 MyBatis 結合 PageHelper 實現分頁功能二、PageHelper 引入 1、依賴引入 pom.xml <properties>...<postgresql.verison>42.5.6</postgresql.ver…

jenkins自動化部署前端vue+docker項目

文章目錄一、準備工作二、編寫dockerfile文件三、新建jenkins任務一、準備工作 默認你的服務器centos已經搭建完成&#xff0c;同時已經安裝了jenkins和docker。 接下來去下載開源項目ruoyi并上傳到自己的gitee中。 二、編寫dockerfile文件 打開項目工程&#xff0c;在rouy…

opencv中contours的使用

一 Contour FindingContours使用 STL-style vector<> 表示&#xff0c;如 vector<cv::Point>, vector<cv::Point2f>。opencv中&#xff0c;使用函數 cv::findContours() 尋找contours&#xff0c; 具體函數定義如下&#xff1a;void cv::findContours(cv::In…

網絡安全初級

1、docker并配置代理 &#xff08;1&#xff09;在Ubuntu中安裝docker apt-get install docker.io docker-compose &#xff08;2&#xff09;安裝完成后&#xff0c;進入/etc/systemd/system/docker.service.d/http-proxy.conf配置文件下進行代理的配置&#xff0c;配置如圖…

JetBrains IDE 性能優化指南:idea.vmoptions 核心參數解析與配置建議

文章目錄深入解析 JetBrains IDE 的 VM 選項&#xff1a;idea.vmoptions 參數詳解一、內存與垃圾回收配置二、診斷與錯誤處理三、運行時優化參數四、模塊系統與反射控制五、特殊參數說明六、配置建議指南深入解析 JetBrains IDE 的 VM 選項&#xff1a;idea.vmoptions 參數詳解…

Datawhale AI夏令營 《基于帶貨視頻評論的用戶洞察挑戰賽》Part .1.

1. 賽題 參賽者需要構建端到端的評論分析系統&#xff0c;完成三大核心任務&#xff1a; 商品識別 輸入&#xff1a;視頻描述文本(video_desc)和標簽(video_tags)輸出&#xff1a;精準識別推廣商品名稱(Xfaiyx Smart Translator/Recorder) 多維情感分析 維度&#xff1a;情感傾…

【博文匯項目全維度測試報告:功能與自動化雙軌驗證】

&#x1f308;個人主頁: Aileen_0v0 &#x1f525;熱門專欄: 華為鴻蒙系統學習|計算機網絡|數據結構與算法 ?&#x1f4ab;個人格言:“沒有羅馬,那就自己創造羅馬~” 文章目錄 項目背景:項目背景與意義&#xff1a;項目概述已實現的主要功能包括&#xff1a;當前系統存在的不足…

Java陷阱之assert關鍵字詳解

Assert.isTrue()方法用于斷言條件是否為真&#xff0c;如果條件不滿足&#xff08;即為false&#xff09;&#xff0c;則會拋出IllegalArgumentException&#xff0c;并附帶預設的錯誤信息。在示例中&#xff0c;當1.23不小于2.23時&#xff0c;方法拋出了異常&#xff0c;顯示…

mysql 散記:innodb引擎和memory引擎對比 sql語句少用函數 事務與長事務

文章目錄innodb引擎和memory引擎對比對比sql 語句&#xff1a;盡可能不使用函數條件隱式轉換隱式類型轉換隱式字符編碼轉換補充問題事務與長事務ACIDread viewMVCC 一致性視圖當前讀view 虛擬表長事務的影響與排查影響排查方法預防innodb引擎和memory引擎對比 innodb引擎是索引…

APK安裝器(安卓端)一鍵解除VX限制!輕松安裝各種手機應用

VX為了防止惡意軟件通過平臺傳播&#xff0c;保障用戶設備安全&#xff0c;會把通過VX發送的 APK 文件自動改成 “apk.1” 格式&#xff0c;這樣就能減少惡意軟件傳播的風險。我平時推薦安卓軟件的時候&#xff0c;有朋友反饋說&#xff0c;文件發到VX里就變成 “apk.1” 了&am…

Debian:從GNOME切換到Xfce

最近為20年前的T43重新安裝了Debian系統&#xff0c;但使用的gnome桌面太卡了。于是換成輕量級的Xfce系統。 1.安裝Xfce sudo apt update sudo apt install xfce4 xfce4-goodies命令中xfce4 是Xfce桌面環境的核心組件&#xff0c;xfce4-goodies 是一些額外的工具和插件&#xf…

徐州服務器租用:BGP線路的特點有哪些?

BGP的中文全稱為邊界網關協議&#xff0c;是指一種運行在傳輸控制協議上的自治系統路由協議&#xff0c;主要的功能就是可以實時控制路由的傳播&#xff0c;同時能夠幫助用戶選擇更合適的路由線路&#xff0c;保證網絡能夠穩定的運行&#xff0c;不會輕易出現網絡卡頓或故障的狀…

Java使用OSHI獲取服務器信息

OSHI可以獲取系統信息&#xff08;CPU、內存、磁盤、網絡等&#xff09;&#xff0c;純Java實現&#xff08;通過JNA訪問本地API&#xff0c;無需安裝本地庫&#xff09;&#xff0c;跨平臺支持。引入依賴<dependency><groupId>com.github.oshi</groupId><…

企業數字化資產管理安全、成本、協作困局難解?

在數字化浪潮席卷全球的今天&#xff0c;3D技術已成為驅動影視動畫、工業設計、建筑可視化等領域創新的核心動力。然而&#xff0c;隨著3D資產規模呈指數級增長&#xff0c;企業正面臨前所未有的管理挑戰&#xff1a;海量模型存儲混亂、版本迭代難以追溯、團隊協作效率低下、知…

力扣面試150題--組合總和

Day 72 題目描述&#xff08;終于理順回溯了&#xff09;思路 這里還是基于模板來說明代碼思路void backtracking(參數) {if (終止條件) {存放結果;return;}for (選擇 : 本層集合中的元素) {處理節點;backtracking(路徑, 選擇列表); // 遞歸撤銷處理; // 回溯} }對于主要函數的…

多客戶端-服務器(select,poll)

多客戶端-服務器結構總結一、普通CS架構的局限性核心問題&#xff1a;單線程中accept&#xff08;阻塞等待連接&#xff09;與read&#xff08;阻塞讀取數據&#xff09;函數互相干擾&#xff0c;無法同時處理多客戶端。本質原因&#xff1a;阻塞型函數需獨立執行&#xff0c;若…

如何使用postman做接口測試?

&#x1f345; 點擊文末小卡片 &#xff0c;免費獲取軟件測試全套資料&#xff0c;資料在手&#xff0c;漲薪更快 常用的接口測試工具主要有以下幾種&#xff1a;Postman: 簡單方便的接口調試工具&#xff0c;便于分享和協作。具有接口調試&#xff0c;接口集管理&#xff0c…

新型網絡架構設計助力智慧醫療降本增效

隨著智慧醫療的快速發展,越來越多的醫院開始布局“互聯網+醫療”服務,通過數字化手段提升醫療服務效率。然而,如何構建一個既穩定可靠又具備靈活擴展能力的醫療網絡,成為醫院數字化轉型中的關鍵問題。本文以某智慧醫療項目為例,探討傳統網絡與SD-WAN結合的最佳實踐。 背景…

一文讀懂現代卷積神經網絡—使用塊的網絡(VGG)

目錄 什么是使用塊的網絡&#xff08;VGG&#xff09;&#xff1f; 一、VGG 的核心思想&#xff1a;用塊&#xff08;Block&#xff09;構建網絡 二、VGG 的網絡結構 三、VGG 的優勢 1. 結構簡潔統一 2. 強大的特征表達能力 3. 小卷積核的計算效率 4. 良好的遷移學習性…

Linux的相關學習

linux 1.文件權限怎么修改 chmod [權限模式] [文件或目錄]1、**數字模式&#xff08;八進制&#xff09;**&#xff1a; chmod 755 myfile.sh # 所有者&#xff1a;rwx (7)&#xff0c;組&#xff1a;r-x (5)&#xff0c;其他用戶&#xff1a;r-x (5) 7 rwx&#xff08;讀寫…