SpringBoot——》 有哪几种读取配置的方式?

推荐:
总结——》【SpringBoot】

一、读取所有文件的配置

1、Environment

@Autowired
private Environment env;
 
// 获取参数
String getProperty(String key);

二、读取application文件的配置

application.yml配置如下:

app:
    id: 5ff576fef194fa22505f4331
    name: demo

1、@Value

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class AppConfig {
    @Value("app.id")
    private Long id;
    @Value("app.name")
    private String name;

    public Long getId() {return id;}
    public void setId(Long id) {this.id = id;}
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
}

2、@ConfigurationProperties

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

@Component
@ConfigurationProperties(prefix = "app")
public class AppConfig {
    private Long id;
    private String name;

    public Long getId() {return id;}
    public void setId(Long id) {this.id = id;}
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
}

三、读取指定文件的配置

注意:@PropertySource不支持yml文件读取,因为使用的是Spring框架底层的PropertiesLoaderUtils工具类进行读取的。

参考:SpringBoot——》@PropertySource不支持yaml、yml读取原因

在资源目录 resources 建立config/app.properties,配置如下:

app.id = 5ff576fef194fa22505f4331
app.name = demo

1、@PropertySource + @Value

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource(value = { "config/app.properties" })
public class AppConfig {
    @Value("${app.id}")
    private Long id;
    @Value("${app.name}")
    private String name;

    public Long getId() {return id;}
    public void setId(Long id) {this.id = id;}
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
}

2、@PropertySource + @ConfigurationProperties

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

@Component
@ConfigurationProperties(prefix = "app")
@PropertySource(value = { "config/app.properties" })
public class AppConfig {
    private Long id;
    private String name;

    public Long getId() {return id;}
    public void setId(Long id) {this.id = id;}
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值