spring框架为我们提供了三种注入方式,分别是 set 注入,构造方法注入,接口注入。接口注入不作要求,下面介绍前两种方式。
- set注入
采用属性的set方法进行初始化,就称为set注入。
(1)给普通字符类型赋值1
2
3
4
5
6
7
8
9
10User.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标签, 指定id,class值,id值不做要求,class值为对象所在的完整路径。bean标签再添加 property 标签,要求,name 值与 User类中对应的属性名称一致。value值就是我们要给User类中的username属性赋的值。
1 | applicationContext.xml |
1 | applicationContext.xml |
(3)给List集合赋值1
2
3
4
5
6
7User.java
public class User{
private List<String> username;
public void setUsername(List<String> username) {
this.username= username;
}
}
1 | applicationContext.xml |
(4)给属性文件中的字段赋值1
2
3
4
5
6
7User.java
public class User{
private Properties props ;
public void setProps(Properties props) {
this.props= props;
}
}
1 | applicationContext.xml |
[注意]:无论给什么赋值,配置文件中
- 构造方法的注入
(1)构造方法只有一个参数时1
2
3
4
5
6
7User.java
public class User{
private String usercode;
public User(String usercode) {
this.usercode=usercode;
}
}
1 | applicationContext.xml |
(2)构造方法只有两个参数时
当参数为非字符串类型时,在配置文件中需要指定类型,如果不指定类型一律按照字符串类型赋值。
当参数类型不一致时,框架是按照字符串的类型进行查找的,因此需要在配置文件中指定是参数的位置 。
<constructor-arg value="admin"index="0"></constructor-arg>
<constructor-arg value="23" type="int"index="1"></constructor-arg>