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