前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring Boot 项目访问依赖 jar 包内部的资源文件的路径问题详解

Spring Boot 项目访问依赖 jar 包内部的资源文件的路径问题详解

作者头像
一个会写诗的程序员
发布2021-07-15 14:19:06
1.2K0
发布2021-07-15 14:19:06
举报

Spring Boot 项目访问依赖 jar 包内部的资源文件的路径问题详解

核心代码行:

Resource[]resources =new PathMatchingResourcePatternResolver().getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +"META-INF/driver.properties");

直接上源码:

package com.bytedance.kunlun.engine.drivermanager; import java.io.InputStream; import java.net.URL; import java.util.*; import com.bytedance.kunlun.sdk.drivermanager.api.Driver; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; public class KunLunDriverManager { /** * 注册进系统的驱动列表 */ private final static MapregisteredDrivers =new HashMap<>(); /** * 驱动配置,配置文件名 */ private static final String DRIVER_PROPS_FILE ="META-INF/driver.properties"; /** * 驱动配置Key,Driver实现class全名 */ private static final String KEY_DRIVER_IMPL ="driver_class_name"; /** * 驱动配置Key,Driver名称 */ private static final String KEY_DRIVER_NAME ="driver_name"; /** * 防止类显示初始化调用 */ private KunLunDriverManager() { } static { try { loadInitialDrivers(); }catch (Exception e) { throw new RuntimeException(e); } } public static Driver getDriver(String driverName) { return registeredDrivers.get(driverName); } /** * 注入driver */ private static void registerDriver(String driverName,Driver driver)throws Exception { if (registeredDrivers.containsKey(driverName)) { throw new Exception("引擎名称重复"); } registeredDrivers.put(driverName, driver); } /** * 扫classpath下的所有DRIVER_PROPS_FILE文件,反射实例化,注入DriverManager */ private static void loadInitialDrivers()throws Exception { Resource[]resources =new PathMatchingResourcePatternResolver().getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +"META-INF/driver.properties"); for (int i =0; i Resource res =resources[i]; URL url =res.getURL(); InputStream in =url.openStream(); Properties props =new Properties(); props.load(in); // 通过反射 new driver instance Driver driver =newDriverByParseProperties(props); if (driver !=null) { registerDriver(props.getProperty(KEY_DRIVER_NAME),driver); } } } /** * 根据Properties配置反射生成Driver */ private static Driver newDriverByParseProperties(Properties props)throws Exception { Classclazz =Class.forName(props.getProperty(KEY_DRIVER_IMPL)); Driver driver = (Driver)clazz.getDeclaredConstructor().newInstance(); return driver.setUp(props); } }

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Spring Boot 项目访问依赖 jar 包内部的资源文件的路径问题详解
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档