yaml配置文件转换为POJO

yaml作为配置文件使用起来比properties更加友好,一方面结构化特性好,而且方便表达复杂的数据结构,比如数组。Spring Boot对yaml的支持也非常好。但是如果没有Spring Boot,如何方便的读取的yaml配置文件呢? 本文介绍一种仿照Spring Boot的,把yaml快速转变为配置类的方法。

引入依赖

  • pom.xml

    com.fasterxml.jackson.dataformat
    jackson-dataformat-yaml
    2.12.1

配置类

  • 配置信息一:MessageQueueProperties
@Data
public class MessageQueueProperties {
    private String master;
    private List topicNames;
    private String consumerGroup;
}
  • 配置信息二:DatabaseProperties
@Data
public class DatabaseProperties {
    private String dbName;
    private String jdbcUrl;
    private String driverClassName;
    private String username;
    private String password;
}
  • 总体应用配置信息:ApplicationProperties
/**
 * 应用的配置信息.
 *
 * @author tenmao
 */
@Slf4j
@Data
public class ApplicationProperties {
    private MessageQueueProperties mq;
    private List databases;
}

配置解析

/**
 * yaml转变成POJO.
 * 仿照Spring Boot的模式,配置文件的优先级如下{{PWD}}/config/application.yml, {{PWD}}/application.yml, {{CLASS_PATH}}/application.yml
 *
 * @author tenmao
 */
@Slf4j
public class TenYamlMain {
    private static final String PROPERTIES_NAME = "application.yml";

    public static void main(String[] args) throws IOException {
        Optional configOpt = getFromConfigDir();
        if (!configOpt.isPresent()) {
            configOpt = getFromPwd();
        }
        if (!configOpt.isPresent()) {
            configOpt = getFromClassPath();
        }
        if (!configOpt.isPresent()) {
            throw new IllegalArgumentException("配置文件不存在");
        }

        //yaml格式配置文件转成配置POJO
        ObjectMapper om = new ObjectMapper(new YAMLFactory());

        ApplicationProperties applicationProperties = om.readValue(configOpt.get(), ApplicationProperties.class);

        log.info("application properties: {}", applicationProperties);
    }


    private static Optional getFromConfigDir() throws IOException {
        try (FileInputStream fis = new FileInputStream("com/tenmao/config/" + PROPERTIES_NAME)) {
            return Optional.of(CharStreams.toString(new InputStreamReader(fis, StandardCharsets.UTF_8)));
        } catch (FileNotFoundException e) {
            return Optional.empty();
        }
    }

    private static Optional getFromPwd() throws IOException {
        try (FileInputStream fis = new FileInputStream(PROPERTIES_NAME)) {
            return Optional.of(CharStreams.toString(new InputStreamReader(fis, StandardCharsets.UTF_8)));
        } catch (FileNotFoundException e) {
            return Optional.empty();
        }
    }

    private static Optional getFromClassPath() throws IOException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

        try (InputStream is = classLoader.getResourceAsStream(PROPERTIES_NAME)) {
            if (is == null) {
                return Optional.empty();
            }
            return Optional.of(CharStreams.toString(new InputStreamReader(is, StandardCharsets.UTF_8)));
        }
    }
}

配置文件application.yml

mq:
  topicNames:
    - topic1
    - topic2
  consumerGroup: consumer_group_1
  master: pulsar://192.168.0.100:6650,192.168.0.101:6650,192.168.0.102:6650
databases:
  -
    dbName: default
    driverClassName: org.postgresql.Driver
    jdbcUrl: jdbc:postgresql://localhost:5433/tenmao
    username: tenmao
    password: tenmao

运行

输出日志:

21:38:23.831 [main] INFO com.tenmao.TenYamlMain - application properties: ApplicationProperties(mq=MessageQueueProperties(master=pulsar://192.168.0.100:6650,192.168.0.101:6650,192.168.0.102:6650, topicNames=[topic1, topic2], consumerGroup=consumer_group_1), databases=[DatabaseProperties(dbName=default, jdbcUrl=jdbc:postgresql://localhost:5433/tenmao, driverClassName=org.postgresql.Driver, username=tenmao, password=tenmao)])

参考

  • Reading and Writing YAML Files in Java with Jackson

你可能感兴趣的:(yaml配置文件转换为POJO)