一:spring容器给bean对象注入属性值
1:注入基本属性值
a. 创建MessageBean类:
1 /** 2 * 3 */ 4 package com.hlcui.dao; 5 6 /** 7 * @author Administrator 8 * 9 */ 10 public class MessageBean { 11 private String name; 12 13 private int age; 14 15 private double salary; 16 17 public String getName() { 18 return name; 19 } 20 21 public void setName(String name) { 22 this.name = name; 23 } 24 25 public int getAge() { 26 return age; 27 } 28 29 public void setAge(int age) { 30 this.age = age; 31 } 32 33 public double getSalary() { 34 return salary; 35 } 36 37 public void setSalary(double salary) { 38 this.salary = salary; 39 } 40 41 public String execute() { 42 System.out.println("name=" + name + "\nage=" + age 43 + "\nsalary=" + salary); 44 return "success"; 45 } 46 47 }
b. 在spring容器配置文件中配置MessageBean对象核心代码:
1 <!-- 配置MessageBean对象 --> 2 <bean id="messageBean" class="com.hlcui.dao.MessageBean"> 3 <property name="name" value="Jack"></property> 4 <property name="age" value="27"></property> 5 <property name="salary" value="12000"></property> 6 </bean>
或者将value元素作为property元素的子元素,效果是一样的
1 <bean id="messageBean" class="com.hlcui.dao.MessageBean"> 2 <property name="name"> 3 <value>Tom</value> 4 </property> 5 <property name="age"> 6 <value>27</value> 7 </property> 8 <property name="salary"> 9 <value>12000</value> 10 </property> 11 </bean>
c. 运行测试方法
1 @Test 2 public void testBaseInject(){ 3 ApplicationContext ac = getApplicationContext(); 4 MessageBean mb = ac.getBean("messageBean", MessageBean.class); 5 mb.execute(); 6 }
通过运行结果可知属性值已经注入到对象中,这种方式在前面已经总结过,就是setter注入。
2:注入集合属性值(List、Set、Map、Properties)
时间: 2024-10-17 10:22:34