Fork me on GitHub

第二章 Spring依赖注入

第二章 Spring依赖注入

spring框架为我们提供了三种注入方式,分别是 set 注入,构造方法注入,接口注入。接口注入不作要求,下面介绍前两种方式。

  1. set注入
    采用属性的set方法进行初始化,就称为set注入。
    (1)给普通字符类型赋值
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    User.java
    public class User {
    private String username;
    public String getUsername() {
    return username;
    }
    public void setUsername(String username) {
    this.username= username;
    }
    }

我们只需要提供属性的 set 方法,然后去属性文件中去配置好让框架能够找到 applicationContext.xml 文件的beans标签。标签 beans中添加bean标签, 指定idclass值,id值不做要求,class值为对象所在的完整路径。bean标签再添加 property 标签,要求,name 值与 User类中对应的属性名称一致。value值就是我们要给User类中的username属性赋的值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
applicationContext.xml
<bean id="userAction"class="com.dsky.spring.action.User" >
<property name="username" value="admin"></property>
</bean>
```
(2)给对象赋值

``` java
User.java
public class User {
private UserService userservice;
public void setUserservice(UserService userservice) {
this.userservice= userservice;
}
}
1
2
3
4
5
6
7
applicationContext.xml
<!--对象的声明-->
<bean id="userService" class="com.dsky.spring.service.UserService"></bean>

<bean id="userAction"class="com.idreamsky.spring.action.User" >
<property name="userservice" ref="userService"></property>
</bean>

(3)给List集合赋值

1
2
3
4
5
6
7
User.java
public class User{
private List<String> username;
public void setUsername(List<String> username) {
this.username= username;
}
}

1
2
3
4
5
6
7
8
9
10
applicationContext.xml
<bean id="userAction"class="com.dsky.spring.action.User" >
<propertynamepropertyname="username">
<list>
<value>zhang,san</value>
<value>lisi</value>
<value>wangwu</value>
</list>
</property>
</bean>

(4)给属性文件中的字段赋值

1
2
3
4
5
6
7
User.java
public class User{
private Properties props ;
public void setProps(Properties props) {
this.props= props;
}
}

1
2
3
4
5
6
7
8
9
10
11
applicationContext.xml
<bean>
<propertynamepropertyname="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>

标签中的 key值是 .properties属性文件中的名称。

[注意]:无论给什么赋值,配置文件中标签的 name属性值一定是和对象中名称一致。

  1. 构造方法的注入
    (1)构造方法只有一个参数时
    1
    2
    3
    4
    5
    6
    7
    User.java
    public class User{
    private String usercode;
    public User(String usercode) {
    this.usercode=usercode;
    }
    }
1
2
3
4
applicationContext.xml
<bean id="userAction"class="com.dsky.spring.action.User">
<constructor-arg value="admin"></constructor-arg>
</bean>

(2)构造方法只有两个参数时
当参数为非字符串类型时,在配置文件中需要指定类型,如果不指定类型一律按照字符串类型赋值。
当参数类型不一致时,框架是按照字符串的类型进行查找的,因此需要在配置文件中指定是参数的位置 。

<constructor-arg value="admin"index="0"></constructor-arg>  
<constructor-arg value="23" type="int"index="1"></constructor-arg>
资料整理来自:http://blog.csdn.net/lishuangzhe7047/article/details/20740835
-------------本文结束感谢您的阅读-------------
坚持技术分享,您的支持将鼓励我继续创作!