1.@Value注解
配置文件resources/application.properties
db.username=root
db.password=amdin
@Component
public class DbConfig {
@Value("${db.username}")
private String username;
@Value("${db.password}")
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
.....
2.@ConfigurationProperties注解
@Component
@ConfigurationProperties(prefix = "db")
public class DbConfig {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
...
3.@PropertySource注解+@Value注解
注:@PropertySource注解不支持yml文件读取
配置文件resources/config/dbconfig.properties
db.username=root
db.password=123456
@Component
@PropertySource("config/dbconfig.properties")
public class DbConfig {
@Value("${db.username}")
private String username;
@Value("${db.password}")
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
...
4.@PropertySource注解+@ConfigurationProperties注解
@Component
@ConfigurationProperties(prefix = "db")
@PropertySource("config/dbconfig.properties")
public class DbConfig {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
...
根据以上方式成功读取的配置,可以通过注入Environment 对象获取