SpringBoot—PropertySource加载Yaml文件

概述

在使用SpringMVC或SpringBoot的过程中,经常需要从配置文件中获取相关的配置项。我们可以使用PropertySource为获取,但是它并不支持加载yaml文件。尤其在SpringBoot中,经常会用到yaml来作为系统配置文件。

编写

1、需要引入Beans

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
</dependency>

2、定义加载yaml类型的属性资源工厂类

YamlPropertySourceFactory.java

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import java.io.IOException;
import java.util.Properties;

public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean bean = new YamlPropertiesFactoryBean();
        bean.setResources(resource.getResource());

        Properties properties = bean.getObject();
        return new PropertiesPropertySource(resource.getResource().getFilename(),properties);
    }
}

2、定义获取yaml的资源类

MinioYamlProperties
import com.dokbok.minio.configuration.factorys.YamlPropertySourceFactory;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@ConfigurationProperties(prefix = "minio")
@PropertySource(value = "classpath:application.yaml",factory = YamlPropertySourceFactory.class)
@Data
public class MinioYamlProperties {
    private String endpoint;
    private String user;
    private String password;
}

3、获取属性

BucketService.java

@Service
public class BucketService {
    private MinioClient minioClient;
    @Autowired
    private MinioYamlProperties minioProperties;

    @PostConstruct
    public void init(){
        minioClient = MinioClient.builder()
                .endpoint(minioProperties.getEndpoint())
                .credentials(minioProperties.getUser(),minioProperties.getPassword())
                .build();
    }
}

留下评论

您的邮箱地址不会被公开。 必填项已用 * 标注