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