Yaml/Yml-配置文件-手动获取配置内容

 需要spring-core、spring-bean依赖

 yml文件:

spring:
  datasource:
    # 数据库连接信息
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3308/springboot?useSSL=false
    username: root
    password: 123456

 java代码:

public static void main(String[] args) {
        Resource resource = new ClassPathResource("application-dev.yml");
        YamlPropertiesFactoryBean yamlBean = new YamlPropertiesFactoryBean();
        yamlBean.setResources(resource);
        Properties properties = yamlBean.getObject();
        if (properties != null) {
            String driver = properties.getProperty("spring.datasource.driver-class-name");
            String url =  properties.getProperty("spring.datasource.url");
            String username = properties.getProperty("spring.datasource.username");
            String password = properties.getProperty("spring.datasource.password");
            System.out.println("driver = " + driver);
            System.out.println("url = " + url);
            System.out.println("username = " + username);
            System.out.println("password = " + password);
        }
}

 测试输出:

driver = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3308/springboot?useSSL=false
username = root
password = 123456

 

posted @ 2020-10-13 19:45  Git_Bug  阅读(690)  评论(0编辑  收藏  举报