springboot读取application.yml文件

本文介绍了如何在Spring Boot 2.2.0.RELEASE和JDK 1.8环境下加载和读取YAML配置文件。示例中展示了加载单个配置文件和多个配置文件的方法,并提供了测试用例,展示如何获取配置项的值。

场景:工具类读取application.yml配置文件信息
记录:NO.237
本例环境
        spring-boot:2.2.0.RELEASE
        jdk:1.8
1.加载单个配置文件

public static Object getYmlPropertyValue(String key) {
  
  Properties properties = null;
  try {
    Resource resource = new ClassPathResource(YML_FILE_01);
    YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
    yamlFactory.setResources(resource);
    properties = yamlFactory.getObject();
  } catch (Exception e) {
    e.printStackTrace();
    return null;
  }
  return properties.get(key);
}

2.加载多个配置文件

public static Properties loadProperties(String... ymlFliePaths) {
  Resource[] resources = null;
  Properties properties = null;
  List<Resource> resourcesList = new ArrayList<Resource>();
  for (String location : ymlFliePaths) {
    Resource resource = new ClassPathResource(location);
    resourcesList.add(resource);
  }
  resources = resourcesList.toArray(new Resource[resourcesList.size()]);
  try {
    YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
    yamlFactory.setResources(resources);
    properties = yamlFactory.getObject();
  } catch (Exception e) {
    e.printStackTrace();
    return null;
  }
  return properties;
}

3.测试main函数

public static void main(String [] args){
    System.out.println("测试开始......");
    System.out.println("单个文件,加载application.yml,打印server.servlet.context-path值:");
    System.out.println(getYmlPropertyValue("server.servlet.context-path").toString());
    System.out.println("加载多个文件:");
    Properties properties = loadProperties(YML_FILE_01,YML_FILE_02);
    System.out.println("打印application.yml中的server.servlet.context-path值:");
    System.out.println(properties.get("server.servlet.context-path").toString());
    System.out.println("打印application-common.yml中的plat.node.service值:");
    System.out.println(properties.get("plat.node.service").toString());
    System.out.println("测试结束......");
}

测试结果:

4.完整测试用例

public class YmlPropertiesLoader {

    private static String YML_FILE_01 = "application.yml";
    private static String YML_FILE_02 = "application-common.yml";
    /**
     * 根据key获取value值
     * 加载一个配置文件
     */
    public static Object getYmlPropertyValue(String key) {

        Properties properties = null;
        try {
            Resource resource = new ClassPathResource(YML_FILE_01);
            YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
            yamlFactory.setResources(resource);
            properties = yamlFactory.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return properties.get(key);
    }
    /**
     * 根据key获取value值
     * 加载多个配置文件
     */
    public static Properties loadProperties(String... ymlFliePaths) {
        Resource[] resources = null;
        Properties properties = null;
        List<Resource> resourcesList = new ArrayList<Resource>();
        for (String location : ymlFliePaths) {
            Resource resource = new ClassPathResource(location);
            resourcesList.add(resource);
        }
        resources = resourcesList.toArray(new Resource[resourcesList.size()]);
        try {
            YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
            yamlFactory.setResources(resources);
            properties = yamlFactory.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return properties;
    }
    //测试主函数
    public static void main(String [] args){
        System.out.println("测试开始......");
        System.out.println("单个文件,加载application.yml,打印server.servlet.context-path值:");
        System.out.println(getYmlPropertyValue("server.servlet.context-path").toString());
        System.out.println("加载多个文件:");
        Properties properties = loadProperties(YML_FILE_01,YML_FILE_02);
        System.out.println("打印application.yml中的server.servlet.context-path值:");
        System.out.println(properties.get("server.servlet.context-path").toString());
        System.out.println("打印application-common.yml中的plat.node.service值:");
        System.out.println(properties.get("plat.node.service").toString());
        System.out.println("测试结束......");
    }
}

以上,感谢

### 如何在 Spring Boot 中从 `application.yml` 文件读取数据库配置 在 Spring Boot 应用程序中,可以通过定义 `application.yml` 或 `application.properties` 来管理应用程序的配置。对于数据库连接的相关参数,通常会使用前缀为 `spring.datasource.*` 的键值对来指定数据源的信息。 以下是关于如何通过 `application.yml` 配置文件读取数据库配置的具体方法: #### 1. 数据库配置项说明 Spring Boot 提供了一组标准的属性用于配置数据库连接[^2]。这些属性可以直接写入 `application.yml` 文件中,并由框架自动加载并应用到相应的组件中。常见的数据库相关配置如下所示: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC username: root password: secret driver-class-name: com.mysql.cj.jdbc.Driver jpa: hibernate: ddl-auto: update show-sql: true properties: hibernate.dialect: org.hibernate.dialect.MySQL8Dialect ``` - **url**: 数据库的 JDBC 连接 URL。 - **username/password**: 访问数据库所需的用户名和密码。 - **driver-class-name**: 所需的 JDBC 驱动类名称(可选)。如果未指定,则根据 URL 自动推断驱动器。 - **hibernate.ddl-auto**: Hibernate DDL 自动生成模式,常见选项有 `create`, `update`, 和 `none` 等[^2]。 - **show-sql**: 是否显示 SQL 查询日志。 #### 2. 使用 @ConfigurationProperties 绑定自定义对象 除了直接利用内置的数据源配置外,还可以通过创建一个 Java 类并将该类标记为 `@ConfigurationProperties(prefix="spring.datasource")` 注解的方式实现更灵活的配置绑定。 下面是一个简单的例子展示如何将 `application.yml` 中的内容映射至 POJO 对象: ```java import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "spring.datasource") public class DatabaseConfig { private String url; private String username; private String password; private String driverClassName; // Getters and Setters } ``` 当此 Bean 被扫描时,Spring 将尝试匹配 `application.yml` 下对应路径下的字段填充到实例变量里去[^2]。 #### 3. 日常开发注意事项 为了确保项目能够正常运行,在实际部署过程中需要注意以下几点事项: - 如果切换不同的环境(比如测试/生产),建议采用 profile 功能区分不同场景下使用的配置文件[^2]; - 敏感信息如密码最好不要硬编码于版本控制系统之中,考虑借助外部化工具或者密钥管理系统保管敏感凭证; ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值