spring如何获取properties配置文件里的属性?
1、属性占位符
2、SpEL表达式
本章讲解第一种方式:属性占位符。
一、在spring中,处理外部值的最简单方式就是声明属性源并通过Spring的Environment来检索属性。例如:
@Configuration
@PropertySource("classpath:/cn/bobyco/spring/app.properties")
public class ExpressiveConfig {
@Autowired
Environment env;
@Bean
public CompactDisk sgtPeppers() {
return new SgtPeppers(env.getProperty("disc.title"), env.getProperty("disc.artist"));
}
}
首先使用@PropertySource注解获取properties源文件。也可以使用@PropertySource(value= {"classpath:/cn/bobyco/spring/app.properties",...})来绑定多个properties源文件。
其次自动装配Environment对象,会将properties文件中的键值对注入到env对象中,通过getProperty来获取key对应的值。注入情况如下图:
二、使用占位符(${...})将值插入到spring bean中。
1、如果依赖组件扫描和自动装配来创建和初始化组件,我们可以使用@Value注解来达到目的。
1)、在成员变量上使用@Value注解
@Component // 声明spring组件
public class Black implements CompactDisk {
@Value("${disc.title}") // 使用@Value注解来获取源文件中disc.title对应的值
private String title;
@Value("${disc.artist}")
private String artist;
public Black() {
super();
// TODO Auto-generated constructor stub
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
@Override
public void play() {
// TODO Auto-generated method stub
System.out.println(this.title + " played by " + this.artist);
}
}
2)、在构造方法上使用@Value注解@Component
public class Black implements CompactDisk {
private String title;
private String artist;
// 注意,在此种方式时不要有无参构造方法
public Black(@Value("${disc.title}") String title, @Value("${disc.artist}") String artist) {
this.artist = artist;
this.title = title
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
@Override
public void play() {
// TODO Auto-generated method stub
System.out.println(this.title + " played by " + this.artist);
}
}