Spring容器三种注入类型

Spring注入有三种方式:java

一、Set注入(使用最多测试

二、构造器注入(使用很少)this

三、接口注入(几乎不用)不作测试了spa


一、Set注入:所谓Set注入就是容器内部调用了bean的Set***方法,注意:xml文件中的名字必定要和对象中属性的名字对应prototype

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;
     }
}

配置文件配置方式code

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 >



二、构造器注入:xml

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
3
4
5
6
7
8
9
10
11
< bean id = "role" class = "com.fz.entity.Role" >
     <!-- 一、使用类型给构造器传参数 -->
     <!-- <constructor-arg type="int" value="1"/>
          <constructor-arg type="java.lang.String" value="管理员"/>
      -->
 
     <!-- 二、使用索引给构造器传参数 -->
     < constructor-arg index = "0" value = "2" />
     < constructor-arg index = "1" value = "超级管理员" />
     <!-- 类型和索引能够结合使用,可是不能同时使用,也就是说构造器里有几个参数,这里也就有几个constructor-arg -->
</ bean >


注意:在这里<bean>标签的名称能够用id也能够用name索引

<bean id="user">和<bean name="user">结果都是同样的,用id和用name的惟一区别就是,name能够使用特殊字符,id则不行。接口

例如:

<bean name="user**" >这样写不会报错,经过getBean也能够获取到

<bean id="user**" >这样写就直接会报错








相关文章
相关标签/搜索