@Value("#{}")和Value("${}")
#{}表示SpEl表达式通常用来获取bean的属性,或者调用bean的某个方法,也可以表示常量
@Value("${}") 可以获取对应属性文件中定义的属性值。
在resources 目录下创建test.properties 配置文件
cat.name=xiaohuamao
cat.age=2
实体类
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@Component
public class Cat {
@Value("${cat.name}")
private String name;
@Value("${cat.age}")
private int age;
@Value("#{9-5}")
private int weight;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
@Override
public String toString() {
return "Cat{" + "name='" + name + '\'' + ", age=" + age + ", weight=" + weight + '}';
}
}
配置类
@Configuration
@PropertySource("classpath:/test.properties")
@ComponentScan("com.example.spring.cap1")
public class Main1Config {
}
测试
@Test
public void tes1() {
AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(Main1Config.class);
ConfigurableEnvironment environment=app.getEnvironment();
String catName=environment.getProperty("cat.name");
System.out.println("-------------------------catName 的名字"+catName);
Cat cat =app.getBean(Cat.class);
System.out.println("cat 对象"+cat );
}