⑤. Bean的依赖注入的数据类型
- ①. 普通数据类型(value) ②. 引用数据类型(ref) ③. 集合数据类型
- ②. 基本数据类型
public class UserDaoImpl implements UserDao { private String company; private int age; public void setCompany(String company) { this.company = company; } public void setAge(int age) { this.age = age; } public void save() { System.out.println(company+"==="+age); System.out.println("UserDao save method running...."); } }
<bean id="userDao" class="com.xiaozhi.dao.impl.UserDaoImpl"> <property name="company" value="TANGZHI"></property> <property name="age" value="15"></property> </bean>
- ③. 引用数据类型(UserService中注入了UserDao)
- ④. 集合类型的注入
//(1).集合数据类型(List<String>)的注入 public class UserDaoImpl implements UserDao { private List<String> strList; public void setStrList(List<String> strList) { this.strList = strList; } public void save() { System.out.println(strList); System.out.println("UserDao save method running...."); } } <bean id="userDao" class="com.xiaozhi.dao.impl.UserDaoImpl"> <property name="strList"> <list> <value>aaa</value> <value>bbb</value> <value>ccc</value> </list> </property> </bean>
//(2). 集合数据类型(List<User>)的注入 public class UserDaoImpl implements UserDao { private List<User> userList; public void setUserList(List<User> userList) { this.userList = userList; } public void save() { System.out.println(userList); System.out.println("UserDao save method running...."); } } <bean id="u1" class="com.xiaozhi.domain.User"/> <bean id="u2" class="com.xiaozhi.domain.User"/> <bean id="userDao" class="com.xiaozhi.dao.impl.UserDaoImpl"> <property name="userList"> <list> <bean class="com.xiaozhi.domain.User"/> <bean class="com.xiaozhi.domain.User"/> <ref bean="u1"/> <ref bean="u2"/> </list> </property> </bean>
//(3). 集合数据类型( Map<String,User> )的注入 public class UserDaoImpl implements UserDao { private Map<String,User> userMap; public void setUserMap(Map<String, User> userMap) { this.userMap = userMap; } public void save() { System.out.println(userMap); System.out.println("UserDao save method running...."); } } <bean id="u1" class="com.xiaozhi.domain.User"/> <bean id="u2" class="com.xiaozhi.domain.User"/> <bean id="userDao" class="com.xiaozhi.dao.impl.UserDaoImpl"> <property name="userMap"> <map> <entry key="user1" value-ref="u1"/> <entry key="user2" value-ref="u2"/> </map> </property> </bean>
//(4). 集合数据类型(Properties)的注入 public class UserDaoImpl implements UserDao { private Properties properties; public void setProperties(Properties properties) { this.properties = properties; } public void save() { System.out.println(properties); System.out.println("UserDao save method running...."); } } <bean id="userDao" class="com.xiaozhi.dao.impl.UserDaoImpl"> <property name="properties"> <props> <prop key="p1">aaa</prop> <prop key="p2">bbb</prop> <prop key="p3">ccc</prop> </props> </property> </bean>