@Value("#{}")与@Value("${}")的区别
@Value(“#{}”) 表示SpEl表达式通常用来获取bean的属性,或者调用bean的某个方法。当然还有可以表示常量
@Value("#{1}")
private int number; //获取数字 1
@Value("#{'Spring Expression Language'}") //获取字符串常量
private String str;
@Value("#{dataSource.url}") //获取bean的属性
private String jdbcUrl;
用 @Value(“${xxxx}”)注解从配置文件读取值的用
@Value("${upload.path}")
private String uploadPath;
特殊场景下,我们想把配置文件的信息,读取并自动封装成实体类,这样我们就可以少写很多配置,这时候,就可以使用@ConfigurationProperties,它可以把同类的配置信息自动封装成实体类。
conn.username=admin
conn.password=kyjufskifas2jsfs
conn.remoteAddress=192.168.1.1
@Component
@ConfigurationProperties(prefix="conn")
public class ConnSettings {
private String username;
private String remoteAddress;
private String password ;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getRemoteAddress() {
return remoteAddress;
}
public void setRemoteAddress(String remoteAddress) {
this.remoteAddress = remoteAddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
@Bean
@ConfigurationProperties(prefix = "conn")
public ConnSettings connSettings(){
return new ConnSettings();
}
@EnableConfigurationProperties注解的作用是:使 @ConfigurationProperties 注解的类生效。
如果一个配置类只配置@ConfigurationProperties注解,而没有使用@Component,那么在IOC容器中是获取不到properties 配置文件转化的bean。@EnableConfigurationProperties 相当于把使用 @ConfigurationProperties 的类进行了一次注入。
@ConfigurationProperties(prefix="conn")
public class ConnSettings {
private String username;
private String remoteAddress;
private String password ;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getRemoteAddress() {
return remoteAddress;
}
public void setRemoteAddress(String remoteAddress) {
this.remoteAddress = remoteAddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
@EnableConfigurationProperties(ConnSettings.class)
public class ConnConfiguration {
}