Spring依赖注入分为两种:构造函数注入和setter方法注入;、
1、构造函数注入的配置文件如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean name="userInfo" class="com.openv.impl.UserInfoImpl"> <constructor-arg> <ref bean="helloWorld"/> </constructor-arg> </bean> <!-- 当构造函数有多个参数时,可以使用constructor-arg标签的index属性,index属性的值从0开始 --> <bean name="helloWorld" class="com.openv.impl.HelloWorld"> <constructor-arg index="0"> <ref bean="fileHello"/> </constructor-arg> <constructor-arg index="1"> <value>I am a learner.</value> </constructor-arg> </bean> <!-- 使用构造子注入时,则使用constructor-arg子标签,来指定构造函数的参数 --> <bean name="fileHello" class="com.openv.impl.HelloStrImpl"> <constructor-arg> <value>helloworld.properties</value> </constructor-arg> </bean> </beans>
在上面的这个配置文件中我们主要有3个类:
com.openv.impl.UserInfoImpl,com.openv.impl.HelloWorld,com.openv.impl.HelloStrImpl
这三个类的构造方法分别为:
this.hStr=hStr;
this.words=words;
}
public HelloStrImpl(String profilename){ this.profilename=profilename; }
UserInfoImpl(HelloWorld helloWorld){ this.helloWorld=helloWorld; }
从结合配置文件和构造方法,可以看出下面几点:1、如果构造方法中的参数类型是标准类型如字符串、数字等,在配置文件中就使用<value></value>来作为输入的参数,如果是用户定义的类那么久需要在配置文件中使用<property><ref/></property>来作为输入的参数。2、如果构造函数中含有多个参数在<constructor-args>中添加index来说明是第几个参数,默然是从0开始的。
2、使用setter方式进行注入的配置文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean name="userInfo" class="com.openv.impl.UserInfoImpl"> <property name="helloWorld"> <ref bean="helloWorld"/> </property> </bean> <!-- 当构造函数有多个参数时,可以使用constructor-arg标签的index属性,index属性的值从0开始 --> <bean name="helloWorld" class="com.openv.impl.HelloWorld"> <property name="hStr"> <ref bean="fileHello"/> </property> <property name="words"> <value>I am a learner.</value> </property> </bean> <!-- 使用构造子注入时,则使用constructor-arg子标签,来指定构造函数的参数 --> <bean name="fileHello" class="com.openv.impl.HelloStrImpl"> <property name="profilename"> <value>helloworld.properties</value> </property> </bean> </beans>
同样的我们也有三个类,名字分别为:
com.openv.impl.UserInfoImpl,com.openv.impl.HelloWorld,com.openv.impl.HelloStrImpl
这3个类中没有显示的构造方法,但是他们三个类有一个共同的特点是:在这些类中都有setter方法,下面是这些类中参数的setter方法:
private String profilename; public void setProfilename(String profilename) { this.profilename = profilename; }
public void sethStr(HelloStr hStr) { this.hStr = hStr; } public void setWords(String words) { this.words = words; }
public void setHelloWorld(HelloWorld helloWorld) { this.helloWorld = helloWorld; }
使用setter方法我们就能通过spring的注入。在配置文件中发生的主要变化就是<constructor-args>变为了<property>。
在真正开发的过程中建议使用setter方法进行注入,setter方法注入时spring开发团队所提倡的,因为构造函数注入可能会出现下面的情况:A类依赖B类,B类依赖C类,C类又依赖A类,在使用构造函数注入时就会出现死锁,而使用setter方法进行注入就可以有效的解决这种情况。
但是,构造函数注入存在也有他的原因,在没有setter方法的遗留代码或者没有源码的第三方类时,使用<contructor-args>是进行开发时很明智的选择。
下面的代码是我做分析的源码