Spring注入有三种方式:
1、Set注入(使用最多)
2、构造器注入(使用不多)
3、接口注入(几乎不用)不做测试了
1、Set注入:所谓Set注入就是容器内部调用了bean的Set***方法,注意:xml文件中的名字一定要和对象中属性的名字对应
1
2
3
4
5
6
7
8
9
public class User {
private Role role;//注意:配置文件中property中name的名字跟这个属性的名字一定要相同,不然会找不到
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}配置文件配置方式
1
2
3
4
5
<bean id="role" class="com.fz.entity.Role"></bean>
<bean name="user" class="com.fz.entity.User" scope="prototype">
<property name="role" ref="role"></property>
</bean>
2、构造器注入:
1
2
3
4
5
6
7
8
9
10
public class Role {
private int id;
private String roleName;
public Role(int id, String roleName) {
super();
this.id = id;
this.roleName = roleName;
}
}构造方法注入需要传参数:1、使用类型传参数 2、使用索引传参数(建议)
1
2
3
4
5
6
7
8
9
10
11
<bean id="role" class="com.fz.entity.Role">
<!-- 1、使用类型给构造器传参数 -->
<!-- <constructor-arg type="int" value="1"/>
<constructor-arg type="java.lang.String" value="管理员"/>
-->
<!-- 2、使用索引给构造器传参数 -->
<constructor-arg index="0" value="2" />
<constructor-arg index="1" value="超级管理员" />
<!-- 类型和索引可以结合使用,但是不能同时使用,也就是说构造器里有几个参数,这里也就有几个constructor-arg -->
</bean>
注意:在这里<bean>标签的名称可以用id也可以用name
<bean >结果都是一样的,用id和用name的唯一区别就是,name可以使用特殊字符,id则不行。
例如:
<bean name="user**" >这样写不会报错,通过getBean也可以获取到
<bean >这样写就直接会报错