1、创建person类
public class Person { /* * 使用@Value赋值: * 1、基本数值 * 2、可以写SpEl;#{} * 3、可以写${}、取出配置文件中(例如properties文件)的值(运行环境变量里面的值) */ @Value("张三") private String name; @Value("#{20-2}") private Integer age; private String school; public Person() { super(); } public Person(String name, Integer age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public Integer getAge() { return age; } public void setName(String name) { this.name = name; } public void setAge(Integer age) { this.age = age; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", school=" + school + "]"; } }
2、创建要加载的外部文件
3、spring配置类中加载外部配置文件
/** * 测试bean的属性赋值的配置 */ @Configuration @PropertySource(value= {"classpath:/person.properties"}) public class MainConfigOfPropertyValue { @Bean("person") public Person person() { return new Person(); } }
4、在person类中的属性赋外部文件中定义的值
public class Person { /* * 使用@Value赋值: * 1、基本数值 * 2、可以写SpEl;#{} * 3、可以写${}、取出配置文件中(例如properties文件)的值(运行环境变量里面的值) */ @Value("张三") private String name; @Value("#{20-2}") private Integer age; @Value("${person.school}") private String school; public Person() { super(); } public Person(String name, Integer age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public Integer getAge() { return age; } public void setName(String name) { this.name = name; } public void setAge(Integer age) { this.age = age; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", school=" + school + "]"; } }
5、定义测试方法进行测试
@Test public void test01() { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValue.class); Object bean = applicationContext.getBean("person"); System.out.println(bean); }
得到结果:
外部文件赋值成功。