登录
首页 >  文章 >  java教程

SpringBoot解析怎么指定Yaml配置文件

来源:亿速云

时间:2024-04-01 09:06:35 106浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《SpringBoot解析怎么指定Yaml配置文件》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

1、自定义配置文件

在resources下创建my.yaml文件,“-”用来表示数组类型,一定要注意空格

my:
  contents:
    - id: 12121
      name: nadasd
    - id: 3333
      name: vfffff

2、配置对象类

创建配置类对象,在类上添加@Component、@PropertySource、@ConfigurationProperties注解。

@Component是将该类交由spring管理,@PropertySource用来指定配置文件及解析Yaml格式,@ConfigurationProperties是将解析后的配置文件属性自动注入该类的属性。

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@PropertySource(value = "classpath:my.yaml", factory = YamlPropertiesSourceFactory.class)
@ConfigurationProperties(prefix = "my")
public class MyProperties {

    private List contents = new ArrayList<>();

    public List getContents() {
        return contents;
    }

    public void setContents(List contents) {
        this.contents = contents;
    }


}

class content {
    private String id;

    private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

@PropertySource注解是Spring用于加载配置文件,@PropertySource属性如下:

  • name:默认为空,不指定Spring自动生成

  • value:配置文件

  • ignoreResourceNotFound:没有找到配置文件是否忽略,默认false,4.0版本加入

  • encoding:配置文件编码格式,默认UTF-8 4.3版本才加入

  • factory:配置文件解析工厂,默认:PropertySourceFactory.class 4.3版本才加入,如果是之前的版本就需要手动注入配置文件解析Bean

Spring Boot 默认不支持@PropertySource读取yaml 文件,需要自定义PropertySourceFactory进行解析。

3、YamlPropertiesSourceFactory

创建YamlPropertiesSourceFactory类用来解析Yaml格式的文件。

import org.springframework.boot.env.YamlPropertySourceLoader;
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.List;
import java.util.Optional;

public class YamlPropertiesSourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource createPropertySource(String name, EncodedResource resource) throws IOException {
        String resourceName = Optional.ofNullable(name).orElse(resource.getResource().getFilename());
        List> yamlSources = new YamlPropertySourceLoader().load(resourceName, resource.getResource());
        return yamlSources.get(0);
    }

}

到这里,我们也就讲完了《SpringBoot解析怎么指定Yaml配置文件》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于SpringBoot,YAML的知识点!

声明:本文转载于:亿速云 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>