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<PropertySource<?>> 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;
}

  • 6
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值