spring中依赖注入有两种方式:
1.通过构造函数注入
2.通过setter方法注入
1.通过构造函数注入
spring通过调用需要进行依赖注入的类的构造方法来完成依赖注入,我们需要写好构造方法,以及配置好构造方法中的参数。
举例
向PersonServiceImpl中注入PersonDao,可采用以下配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<!-- 由 Spring容器创建该类的实例对象 -->
<bean id="personDaoImpl" class="com.sp.PersonDaoImpl"></bean>
<bean id="personServiceImpl" class="com.sp.PersonServiceImpl">
<constructor-arg ref="personDaoImpl"></constructor-arg>
</bean>
</beans>
constructor-arg元素中便是对构造函数的参数的配置,我们可以通过构造方法中的参数的索引值来确定是哪个constructor-arg元素对应哪个参数,使用index属性在元素中进行配置。也可以直接使用ref来引用其它bean,spring会根据引用的类型与参数进行匹配。
2.通过setter方法注入
依赖方要提供被依赖方的setter方法,并且要在配置文件中进行配置。与1中不同的是使用的为property标签,每一个property元素对应一个实现了setter方法的类属性。并且通过依赖类中被依赖类的对象名来确定。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<!-- 由 Spring容器创建该类的实例对象 -->
<bean id="personDaoImpl" class="com.sp.PersonDaoImpl"></bean>
<bean id="personServiceImpl" class="com.sp.PersonServiceImpl">
<property name="personDao" ref="personDaoImpl"></property>
</bean>
</beans>