依赖注入方式总概括为三种:
1、setter注入
2、构造器注入
3、接口注入(不推荐)
例bean:
public class Student {
private String stuName;
private Integer stuAge;
public Student() {
System.out.println('Student创建了');
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public Integer getStuAge() {
return stuAge;
}
public void setStuAge(Integer stuAge) {
this.stuAge = stuAge;
}
}
1、setter注入
Spring配置文件(ioc.xml)
方式一:
value属性
<bean id='Student01' class='BeanDemo.Demo01.Student'>
<property name='stuName' value='小明'></property>
<property name='stuAge' value='20'></property>
</bean>
方式二:
value标签
<bean id='Student01' class='BeanDemo.Demo01.Student'>
<property name='stuName'>
<value>小明</value>
</property>
<property name='stuAge'>
<value>20</value>
</property>
</bean>
方式三:
p命名空间
<bean id='Student01' class='BeanDemo.Demo01.Student' p:stuName='小王' p:stuAge='45'></bean>
扩展:对对象的属性赋值为null
使用null标签
<bean id='Student01' class='BeanDemo.Demo01.Student'>
<property name='stuName'><null/></property>
<property name='stuAge' value='20'></property>
</bean>
2、构造器注入:
Spring配置文件(ioc.xml)
方式一:
name+value
<bean id='Student01' class='BeanDemo.Demo01.Student'>
<constructor-arg name='stuName' value='小张'></constructor-arg>
<constructor-arg name='stuAge' value='25'></constructor-arg>
</bean>
方式二:
value+index
<bean id='Student01' class='BeanDemo.Demo01.Student'>
<constructor-arg value='小张' index='0'></constructor-arg>
<constructor-arg value='25' index='1'></constructor-arg>
</bean>
方式三:
value+index+type
<bean id='Student01' class='BeanDemo.Demo01.Student'>
<constructor-arg value='小张' index='0' type='java.lang.String'></constructor-arg>
<constructor-arg value='25' index='1' type='java.lang.Integer'></constructor-arg>
</bean>