栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot读取配置文件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot读取配置文件

一.读取springboot框架自带的application.properties或application.yml文件.

1.通过@Value注解来读取

application.properties文件内容:

name=1

user.name=2

读取方式:

@Value("${name}")
private String name;

@Value("${user.name}")
private String userName;

如果要设置默认值:

@Value("${name:张三}")
private String name;

//设置默认值为空置
@Value("${user.name:#{null}}")
private String userName;

2.通过@ConfigurationProperties(prefix="***")来读取

@Data
@Component
@ConfigurationProperties(prefix="user")
public class TestBean{

    String name;
}
二.读取springboot中自定义的properties文件,例如test.properties

1.通过@Value和@PropertySource结合取值

@Component
@PropertySource("classpath:test.properties")
public class TestBean{

    @Value("${name}")
    private String name;

    @Value("${user.name}")
    private String userName;
}

2.通过@ConfigurationProperties和@PropertySource结合取值

@Component
@ConfigurationProperties(prefix="user")
@PropertySource("classpath:test.properties")
public class TestBean{

    String name;

}
三.读取springboot中自定义的yml文件,例如test.yml

1.通过@Value和@PropertySource

import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;

import java.io.IOException;
import java.util.List;

public class PropertySourceFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource createPropertySource(String name, EncodedResource resource) throws IOException {
        if (resource == null) {
            return super.createPropertySource(name, resource);
        }
        List> sources = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource());
        return sources.get(0);
    }
}

@Component
@PropertySource(value="test.yml",factory=PropertySourceFactory.class)
public class TestBean{

    @Value("${name}")
    private String name;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/777631.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号