上篇文章说到了构造器注入,但是有时候构造器注入并不是很好用,现在来看下set注入。
构造器注入博客地址:http://blog.csdn.net/luckey_zh/article/details/46671307
看下例子:
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=张三]]
时间: 2024-10-14 00:59:05