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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM