1 @RefreshScope
作用:文件自动刷新
2@ConfigurationProperties
作用:读取文件的配置信息
配置文件:
connection.username=admin
connection.password=kyjufskifas2jsfs
connection.remoteAddress=192.168.1.1
@Setter
@Getter
@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {
private String username;
private String remoteAddress;
private String password ;}
3几种配置文件的对比
(1)添加properties文件
info:
name: xiaoming
age: 13 sex: 1
1@value读取
@Setter
@Getter
@Component
public class TechUser {
@Value("${info.name}")
private String name;
@Value("${info.age}")
private int age;
@Value("${info.sex}")
private int sex;}
2ConfigurationProperties
@Component
@ConfigurationProperties(prefix = "info")
public class TechUser {
private String name;
private int age;
private int sex;}
读取指定文件
文件config/db-config.properties
db.username=root
db.password=123456
@PropertySource+@Value注解读取方式
@Component 这个不用get和set
@PropertySource(value = { "config/db-config.properties" })
public class DBConfig1 {
@Value("${db.username}")
private String username;
@Value("${db.password}")
private String password;}
注意:@PropertySource不支持yml文件读取。
2.2@PropertySource+@ConfigurationProperties注解读取方式
@Component
@ConfigurationProperties(prefix = "db")
@PropertySource(value = { "config/db-config.properties" })
public class DBConfig2 {
private String username;
private String password;}
3.Environment读取方式
@Autowired private Environment env;