如何在Lombok @UtilityClass中程序化读取resource.yaml配置值
针对Lombok @UtilityClass的resource.yaml配置程序化读取实现
由于@UtilityClass会将类转为全静态结构,无法使用Spring的@Value注解注入配置,以下是两种可行的程序化读取方案:
方案一:Spring环境下使用Spring自带工具类
如果你的项目是Spring/Spring Boot项目,直接用Spring的YAML解析工具更贴合生态:
@UtilityClass public class UtilityClass { private static final String TARGET_RESOURCE = readFromFile("path.to.resource"); private static String readFromFile(String path) { // 加载classpath下的resource.yaml文件 org.springframework.core.io.Resource resource = new org.springframework.core.io.ClassPathResource("resource.yaml"); try { org.springframework.beans.factory.config.YamlPropertiesFactoryBean yamlFactory = new org.springframework.beans.factory.config.YamlPropertiesFactoryBean(); yamlFactory.setResources(resource); java.util.Properties properties = yamlFactory.getObject(); // 按配置路径获取对应值 return properties.getProperty(path); } catch (Exception e) { throw new RuntimeException("读取resource.yaml配置失败", e); } } }
方案二:通用环境下使用SnakeYAML库
如果项目不依赖Spring,可以引入SnakeYAML库(Maven依赖:org.yaml:snakeyaml:2.2)来解析YAML:
@UtilityClass public class UtilityClass { private static final String TARGET_RESOURCE = readFromFile("path.to.resource"); private static String readFromFile(String path) { org.yaml.snakeyaml.Yaml yaml = new org.yaml.snakeyaml.Yaml(); try (java.io.InputStream inputStream = UtilityClass.class.getClassLoader().getResourceAsStream("resource.yaml")) { // 将YAML解析为嵌套Map结构 java.util.Map<String, Object> yamlMap = yaml.load(inputStream); // 拆分配置路径,逐层遍历获取值 String[] keySegments = path.split("\\."); Object currentValue = yamlMap; for (String segment : keySegments) { if (!(currentValue instanceof java.util.Map)) { return null; // 配置路径不存在 } currentValue = ((java.util.Map<?, ?>) currentValue).get(segment); if (currentValue == null) { break; } } return currentValue != null ? currentValue.toString() : null; } catch (Exception e) { throw new RuntimeException("读取resource.yaml配置失败", e); } } }
注意事项
- 确保
resource.yaml文件放置在src/main/resources目录下(classpath根路径)。 - 异常处理可根据业务需求调整,比如返回默认值而非抛出运行时异常。
- 嵌套配置路径(如
parent.child.key)会被自动拆分并逐层取值。
内容的提问来源于stack exchange,提问作者Kalec
相关产品推荐
相关产品推荐

