- 使用 @Value赋值
- 1.基本数值
-
- springEL :#{}
- 3.可以写${}:取出配置文件【properties】的值(在运行环境变量中的值)
@Value("张三")
private String name;
@Value("#{20-2}")
private Integer age;
@Value("${jdbc.username}")
private String userName;
@Configuration //标注这是一个配置类
//使用PropertySource读取外部属性文件中k/v保存到运行环境变量中;加载完外部的属性文件以后使用${}取出配置文件中的值
@PropertySource(value = {"/jdbc.properties"})
public class MainConfigOpenValue {
@Bean("personTwo")
public Person person(){
return new Person();
}
}
测试类
public class TestTwo {
AnnotationConfigApplicationContext apx = new AnnotationConfigApplicationContext(MainConfigOpenValue.class);
@Test
public void Import(){
Person person = (Person) apx.getBean("personTwo");
//获取到环境变量
ConfigurableEnvironment environment = apx.getEnvironment();
//根据环境变量中的key 来获取到value值
String property = environment.getProperty("jdbc.username");
System.out.println(property);
System.out.println(person);
}
本文详细介绍了Spring框架中@Value注解的使用方法,包括基本数值赋值、表达式计算及从配置文件中读取属性值。通过示例展示了如何在配置类中使用@PropertySource指定属性文件,并在Bean中注入属性值。
948

被折叠的 条评论
为什么被折叠?



