spring框架为我们提供了三种注入方式,分别是set注入,构造方法注入,接口注入。接口注入不作要求,下面介绍前两种方式。
1,set注入
采用属性的set方法进行初始化,就成为set注入。
1)给普通字符类型赋值。
public class user{
privatestring username;
publicstring getusername() {
returnusername;
}
publicvoid setusername(string username) {
this.username= username;
}
}
我们只需要提供属性的set方法,然后去属性文件中去配置好让框架能够找到applicationcontext.xml文件的beans标签。标签beans中添加bean标签,
指定id,class值,id值不做要求,class值为对象所在的完整路径。bean标签再添加property
标签,要求,name值与user类中对应的属性名称一致。value值就是我们要给user类中的username属性赋的值。
<bean id="useraction"class="com.lsz.spring.action.user" >
<property name="username" value="admin"></property>
</bean>
2)给对象赋值
同样提供对象的set方法
public class user{
private userservice userservice;
public userservicegetuserservice() {
returnuser;
}
public void setuserservice(userservice userservice){
this.userservice= userservice;
}
}
配置文件中要增加userservice的bean标签声明及user对象对userservice引用。
<!--对象的声明-->
<bean id="userservice" class="com.lsz.spring.service.userservice"></bean>
<bean id="useraction"class="com.lsz.spring.action.user" >
<property name="userservice" ref="userservice"></property>
</bean>
这样配置,框架就会将userservice对象注入到user类中。
3)给list集合赋值
同样提供set方法
public class user{
privatelist<string> username;
publiclist<string> getusername() {
returnusername;
}
publicvoid setusername(list<string> username) {
this.username= username;
}
}
<bean id="useraction"class="com.lsz.spring.action.user" >
<propertyname="username">
<list>
<value>zhang,san</value>
<value>lisi</value>
<value>wangwu</value>
</list>
</property>
</bean>
4)给属性文件中的字段赋值
public class user{
privateproperties props ;
publicproperties getprops() {
returnprops;
}
publicvoid setprops(properties props) {
this.props= props;
}
}
<bean>
<propertyname="props">
<props>
<propkey="url">jdbc:oracle:thin:@localhost:orl</prop>
<propkey="drivername">oracle.jdbc.driver.oracledriver</prop>
<propkey="username">scott</prop>
<propkey="password">tiger</prop>
</props>
</property>
</bean>
<prop>标签中的key值是.properties属性文件中的名称
注意:
无论给什么赋值,配置文件中<property>标签的name属性值一定是和对象中名称一致。
2构造方法注入
1)构造方法一个参数
public class user{
privatestring usercode;
publicuser(string usercode) {
this.usercode=usercode;
}
}
<bean id="useraction"class="com.lsz.spring.action.user">
<constructor-argvalue="admin"></constructor-arg>
</bean>
2)构造函数有两个参数时
当参数为非字符串类型时,在配置文件中需要制定类型,如果不指定类型一律按照字符串类型赋值。
当参数类型不一致时,框架是按照字符串的类型进行查找的,因此需要在配置文件中制定是参数的位置
<constructor-argvalue="admin"index="0"></constructor-arg>
<constructor-argvalue="23" type="int"index="1"></constructor-arg>
这样制定,就是构造函数中,第一个参数为string类型,第二个参数为int类型
以上就是spring框架学习(二)依赖注入的内容。