读取SpringBoot配置文件的几种方式

一、背景

在SpringBoot开发过程中,通常需要在*.properties/*.yml写配置内容,那么应用程序有哪几种读取配置文件内容的方式呢?

二、实践

下面介绍读取SpringBoot配置文件*.properties/*.yml的几种种方式。  
(1)@Value()  
通过@Value()来读取,格式如下:
```
@Value("${配置属性:默认值}")
```
配置默认值是为了防止程序读取不到配置而报错,所有的前提是该类必须是Bean,否则@Value()不会生效。
但如果是static或final,那么@Value也不会生效。
// 举例
class Test{
    @Value("${jwt.secret:}") // jwt.secret 或 “”
    private String jwtSecret;
}
(2)@ConfigurationProperties()  
如果同个类需要配置多个@Value(),但很麻烦,那么可以使用@ConfigurationProperties()统一批量配置:
// 举例
@ConfigurationProperties(prefix = "jwt")
class Test {
    private String jwtSecret;
}
(3)Environment  
Environment是SpringBoot底层核心配置API,它提供了简单的方法来访问应用程序属性,包括系统属性、操作系统环境变量、命令行参数、应用程序配置文件的属性等。
// 举例
class Test {
    @Resource
    private Environment env;

    @Test
    public void readEnv() {
        String var = env.getProperty("jwt.secret");
    }
}

// or 
class Test implements EnvironmentAware {
    private Environment env;

    @Test
    public void readEnv() {
        String var = env.getProperty("jwt.secret");
    }
    
    @Override
    public void setEnvironment(Environment env){
        this.env = env;
    }
}
(4)读取自定义配置文件  
要读取自定义配置文件(如*.property),需要使用@PropertySources()导入文件,在使用@Value读取:
// 举例
@PropertySources({
        @PropertySource(value = "classpath:jwt.properties",encoding = "utf-8")
})
class Test {
    @Value("${jwt.secret:}") // jwt.secret 或 “”
    private String jwtSecret;
}
读取*.yml,需要单独配置,再通过@Value读取:
// 举例
@Configuration
public class YamlConfig {
    @Bean
    public static PropertySourcesPlaceholderConfigurer yamlConfig() {
        PropertySourcesPlaceholderConfigurer config = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yaml=new YamlPropertiesFactoryBean();
        yaml.setResources(new ClasspathResource("*.yml"));
        configure.setProperties(Object.require(yaml.getObject()));
    }
}

class Test {
    @Value("${jwt.secret:}") // jwt.secret 或 “”
    private String jwtSecret;
}
(五)Java原生读取
class ReadConfig {
    public void readConfig() {
        Properties props = new Properties();
        try {
            InputStreamReader reader = new InputStreamReader(
                    this.getClass().getClassLoader().getResourceAsStream("*.properties"),
                    StandardCharsets.UTF_8
            );
            props.load(reader);
        }catch (IOException e){
            System.out.println(e);
        }
        // 使用
        System.out.println(props.getProperty("jwt.secret"));
    }
}

我们一般值使用到前面三种,前面三种比较使用,下面两种很少使用。

三、参考

1. https://v.douyin.com/iesV7bgE/

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值