从.yml配置文件中读取属性值

该博客介绍了如何在SpringBoot中自定义YamlPropertySourceFactory类,以便从.yml配置文件中读取属性值。通过覆盖`createPropertySource`方法,实现了对.properties、.yml和.yaml文件的支持。示例代码展示了如何关联配置类并使用@PropertySource注解从test.yml加载配置。

从.yml配置文件中读取属性值


参考文章

springboot使用@PropertySource的默认factory是读取.properties文件属性。
如果要读取yml或者yaml格式的文件属性值,需要自定义一个YamlPropertySourceFactory

实现YamlPropertySourceFactory类
package com.example.demo.config;

import lombok.AllArgsConstructor;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;


public class YamlPropertySourceFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource)
            throws IOException {

        // 指定配置路径中的文件名
        String filename = resource.getResource().getFilename() == null ? "" : resource.getResource().getFilename();

        // 资源为空,则会抛出异常
        resource.getInputStream();

        // 配置文件为 properties 文件,调用原逻辑
        if (resource == null || filename.endsWith(".properties")) {
            return super.createPropertySource(name, resource);
        }
        // yml文件 或 yaml文件,则使用yaml属性源加载器加载并返回标准属性源
        else if (filename.endsWith(".yml") || filename.endsWith(".yaml")) {
            return new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource()).get(0);
        }
        // 非以上情况,则直接抛出异常,提示格式错误
        else {
            throw new IOException("file format error! only support: properties, yml, yaml!");
        }
    }
}
关联的对象类

通过@PropertySource来指定配置文件路径

package com.example.demo.config;

import lombok.Data;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.io.Serializable;

@ConfigurationProperties(prefix = "test")
@Component
@PropertySource(value="classpath:test.yml",factory = YamlPropertySourceFactory.class, encoding = "utf-8")
@Data
public class TestConfig implements Serializable{
    private String userName;
    private String password;
}

在Spring Boot应用中,读取`application.yml`配置文件是非常常见的操作,它允许开发者将环境变量和系统属性存储在独立的配置文件中,而不是硬编码到代码。`application.yml`通常包含了应用程序的一些基本配置,如数据库连接信息、邮件服务器配置等。 为了读取`application.yml`,首先需要在Spring Boot项目的pom.xml或build.gradle文件中添加对Spring Boot Actuator或Spring Cloud Config的支持,以便支持配置文件的动态加载。 对于Java配置(使用@ConfigurationProperties注解): 1. 首先在你的配置类上添加`@ConfigurationProperties(prefix="app")`,其中"app"是你在YAML文件中定义配置项前缀的别名: ```java @ConfigurationProperties(prefix = "app") public class AppConfig { private String databaseUrl; private int port; // getters and setters... } ``` 2. 在`application.yml`中编写配置: ```yaml app: databaseUrl: jdbc:mysql://localhost/mydb port: 8080 ``` 然后通过@Autowired注入AppConfig实例即可访问配置值: ```java @Autowired private AppConfig appConfig; ``` 对于YAML配置(使用`@Profile`和`@ConditionalOnProperty`): 如果你想要基于特定环境(如dev、prod)加载不同的配置,可以使用`@Profile`。例如: ```java @Configuration @Profile("dev") @ConfigurationProperties(prefix = "app.dev") public class DevAppConfig { // ... } @Configuration @Profile("prod") @ConfigurationProperties(prefix = "app.prod") public class ProdAppConfig { // ... } ``` 在启动应用时,Spring会自动选择相应的配置。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值