核心代码行:
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); } }