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

Posted 东海陈光剑

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot 项目访问依赖 jar 包内部的资源文件的路径问题详解相关的知识,希望对你有一定的参考价值。

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);

}

}

以上是关于Spring Boot 项目访问依赖 jar 包内部的资源文件的路径问题详解的主要内容,如果未能解决你的问题,请参考以下文章

spring boot 使用maven打包删除配置文件

Spring Boot 无法访问依赖 jars 类路径中的资源

Spring boot demo: spring boot生成war包

spring boot学习02如何在spring boot项目中访问jsp

spring项目jar包内的配置文件和项目的配置文件有重复项

为依赖于其他项目的 Spring Boot 应用程序创建胖 jar 时出现异常