时间:2020-10-09 13:10:57 | 栏目:JAVA代码 | 点击:次
这篇文章主要介绍了Spring @value和@PropertySource注解使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
public class Cat {
@Value("猫") //直接注入字符串
private String name;
@Value("#{12+2}") //支持EL表达式
private int age;
@Value("${parent}") //支持配置文件读取
private String parent;
public Cat() {
System.out.println("猫被初始化");
}
@Override
public String toString() {
return "Cat{" +
"name='" + name + '\'' +
", age=" + age +
", parent='" + parent + '\'' +
'}';
}
}
@Import({Cat.class})
@PropertySources({@PropertySource(value ="cat.properties")})
public class Appconfig {
}
public class Demo {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Appconfig.class);
Cat bean = context.getBean(Cat.class);
System.out.println(bean); //Cat{name='猫', age=14, parent='tiger'}
ConfigurableEnvironment environment = context.getEnvironment();
System.out.println(environment.getProperty("parent")); //tiger
}
}
