上面的操作,都是注入的引用Bean,处了对象的引用可以注入,普通数据类型,集合等都可以在容器中进行注入。
注入数据的三种数据类型
普通数据类型
引用数据类型
集合数据类型
其中引用数据类型,此处就不再赘述了,之前的操作都是对UserDao对象的引用进行注入的,下面将以set方法注入为例,演示普通数据类型和集合数据类型的注入。
Bean的依赖注入的数据类型
(1)普通数据类型的注入
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.leon.dao.impl.UserDaoImpl"> <property name="company" value="leon"></property> <property name="age" value="15"></property> </bean>(2)集合数据类型(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.leon.dao.impl.UserDaoImpl"> <property name="strList"> <list> <value>aaa</value> <value>bbb</value> <value>ccc</value> </list> </property> </bean>(3)集合数据类型(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.leon.domain.User"/> <bean id="u2" class="com.leon.domain.User"/> <bean id="userDao" class="com.leon.dao.impl.UserDaoImpl"> <property name="userList"> <list> <bean class="com.leon.domain.User"/> <bean class="com.leon.domain.User"/> <ref bean="u1"/> <ref bean="u2"/> </list> </property> </bean>(4)集合数据类型( 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.leon.domain.User"/> <bean id="u2" class="com.leon.domain.User"/> <bean id="userDao" class="com.leon.dao.impl.UserDaoImpl"> <property name="userMap"> <map> <entry key="user1" value-ref="u1"/> <entry key="user2" value-ref="u2"/> </map> </property> </bean>(5)集合数据类型(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.leon.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>