上篇文章说到了构造器注入。可是有时候构造器注入并非非常好用,如今来看下set注入。


看下样例:

public class Roles {
private int id;
private String roleName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
//重写toString方法。方便測试
@Override
public String toString() {
return "Roles [id=" + id + ", roleName=" + roleName + "]";
}
}

spring配置:

<bean id="roles" class="cn.com.ztz.spring.model.Roles">
<property name="id" value="2"/>
<property name="roleName" value="管理员"/>
</bean>


測试main方法:

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
Roles r=(Roles)context.getBean("roles");
System.out.println(r.toString());
}



输出结果:

Roles [id=2, roleName=管理员]


看spring配置。我们能发现构造器<constructor-arg/> set注入是<property/> 


一个bean引用其它的bean也是几乎相同的。看下样例

public class Roles {
private int id;
private String roleName;
private Users users;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public void setUsers(Users users) {
this.users = users;
}
public Users getUsers() {
return users;
}
//重写toString方法,方便測试
@Override
public String toString() {
return "Roles [id=" + id + ", roleName=" + roleName + ", users="
+ users + "]";
}
}
public class Users {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "Users [id=" + id + ", name=" + name + "]";
}
}


spring配置:

<bean id="roles" class="cn.com.ztz.spring.model.Roles">
<property name="id" value="2"/>
<property name="roleName" value="管理员"/>
<property name="users" ref="users"/>
</bean>

<bean id="users" class="cn.com.ztz.spring.model.Users">
<property name="id" value="2"/>
<property name="name" value="张三"/>
</bean>

执行以上測试方法输出结果:

Roles [id=2, roleName=管理员, users=Users [id=2, name=张三]]