Spring—依赖注入
依赖注入(DI): 应用程序所需资源由IoC容器提供,而资源进入应用程序的方式便是DI,简单理解就是"属性赋值",可以赋值引用数据类型和非数据类型的。
依赖注入的方式可分为:set注入(主流配置)和构造器注入(兼容早期遗留系统的升级工作)。
(一) Set 注入
1、注入引用数据类型
通常情况下,声明引用类对象,提供set()方法,调用引用类对象方法,注入引用类bean实例。
public class UserServiceImpl implements UserService {
//1.声明引用类对象
private UserDao userDao;
//2.提供set()方法
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void run() {
System.out.println("注入引用类型");
//3.调用引用类方法
userDao.show();
}
}
<!--set注入引用类型-->
<bean id="userService" class="com.mine.service.impl.UserServiceImpl">
<!--
2.引入类型变量通过proprety属性注入,name是变量名,ref声明注入bean的id
-->
<property name="userDao" ref="userDao"/>
</bean>
<!--1.声明注入的bean-->
<bean id="userDao" class="com.mine.dao.impl.UserDaoImpl"/>
2、注入非引用数据类型
通常情况下,声明非引用类型属性,提供set()方法,直接使用属性,注入属性值即可。
public class UserServiceImpl implements UserService {
//1.声明注入的非引用变量;
private int num;
private String gender;
//2.提供set方法
public void setNum(int num) {
this.num = num;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public void run() {
//3.调用非引用类型属性
System.out.println("set注入非引用类型"+":"+num+"..."+gender);
}
}
<bean id="userService" class="com.mine.service.impl.UserServiceImpl">
<!--4.为属性赋值,name是变量名,value是变量值-->
<property name="num" value="20"/>
<property name="gender" value="女"/>
</bean>
3.注入集合类型属性
3.1 List
<property name="集合对象">
<list>
<!--注入非引用数据类型-->
<value>6666</value>
<!--注入引用的数据类型-->
<ref bean="userService"/>
<bean class="com.mine.service.impl.UserServiceImpl"/>
</list>
</property>
3.2 数组
<property name="数组对象">
<array>
<!--注入非引用数据类型-->
<value>6666</value>
<!--注入引用的数据类型-->
<ref bean="userService"/>
<bean class="com.mine.service.impl.UserServiceImpl"/>
</array>
</property>
3.3 hashSet
<property name="hashSet对象">
<set>
<!--注入非引用数据类型-->
<value>6666</value>
<!--注入引用的数据类型-->
<ref bean="userService"/>
<bean class="com.mine.service.impl.UserServiceImpl"/>
</set>
</property>
3.4 hashMap
<property name="hashMap对">
<map>
<entry key="age" value-ref="20"/>
<entry key="name" value-ref="mine"/>
<entry key="userService">
<ref bean="userService"/>
</entry>
<entry key="applySerevice">
<bean class="applySerevice"/>
</entry>
</map>
</property>
3.5 props
<property name="properties对象">
<props>
<prop key="loginName">张三</prop>
<prop key="password">123</prop>
</props>
</property>
(二) 构造器注入
通常情况下,声明属性,提供构造方法,注入属性值即可。
public class UserServiceImpl implements UserService {
//1.声明含有引用和非引入类型的变量
private UserDao userDao;
private int num;
private String gender;
//2.提供构造方法
public UserServiceImpl(){}
public UserServiceImpl(UserDao userDao, int num, String gender) {
this.userDao = userDao;
this.num = num;
this.gender = gender;
}
<!--1.声明注入的bean-->
<bean id="userDao" class="com.mine.dao.impl.UserDaoImpl"/>
<!--2.构造器注入属性值-->
<bean id="userService" class="com.mine.service.impl.UserServiceImpl">
<constructor-arg name="userDao" ref="userDao"/>
<constructor-arg name="num" value="30"/>
<constructor-arg name="gender" value="男"/>
</bean>