属性赋值@Value的使用
设置默认值
@Value("iphoneX")
private String name;
Spring EL表达式
@Value("#{10000*0.8}")
private int money;
读取配置文件
@PropertySource(读取指定配置文件到环境变量中)
使用 @PropertySource
读取外部配置文件中的k/v保存到运行的环境变量中;加载完外部的配置文件以后使用 ${}
取出配置文件的值
@Configuration
@PropertySource("classpath:/phone.properties")
public class BeanConfig6 {
@Bean
public Phone phone(){
return new Phone();
}
}
${}格式读取配置文件
@Value("${phone.comment}")
private String comment;
三种写法
@Value("iphoneX")
private String name;
@Value("#{10000*0.8}")
private int money;
@Value("${phone.comment}")
private String comment;
java方式获取配置值
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig6.class);
ConfigurableEnvironment environment = context.getEnvironment();
String key = environment.getProperty("phone.comment");