1、創建Person類
public class Person { private String name; private Integer age; 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; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } }
2、spring配置類中注入Person
/** * 測試bean的屬性賦值的配置 */ @Configuration public class MainConfigOfPropertyValue { @Bean("person") public Person person() { return new Person(); } }
3、創建測試方法測試
@Test public void test01() { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValue.class); Object bean = applicationContext.getBean("person"); System.out.println(bean); }
得到結果:

4、此時我們利用@Value進行賦值,修改Person類
public class Person { /* * 使用@Value賦值: * 1、基本數值 * 2、可以寫SpEl;#{} * 3、可以寫${}、取出配置文件中(例如properties文件)的值(運行環境變量里面的值) */ @Value("張三") private String name; @Value("#{20-2}") private Integer age; 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; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } }
再次運行測試方法得到:

