spring bean初始化
程序员文章站
2022-05-21 19:18:30
...
声明角色bean
public class Roles{
private int id;
private String roleName;
private Roles(){}
private Roles(int id , String roleName){
this.id = id;
this.roleName = roleName;
}
@Override
public String toString(){
return "Users [ id=" + id + ",name=" + roleName + "]" ;
}
}
spring配置
<bean id="roles" class="cn.com.ztz.spring.model.Roles">
<constructor-arg value="1"/>
<constructor-arg value="管理员"/>
</bean>
测试
public class SpringTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
Roles u = (Roles)context.getBean("roles");
System.out.println(u.toString());
}
}
=========================================================
Roles.java
public class Roles {
private int id;
private String roleName;
//用户
private Users users;
public Roles() {
}
public Roles(int id,String roleName,Users users) {
this.id=id;
this.roleName = roleName;
this.users=users;
}
//重写toString方法,方便测试
@Override
public String toString() {
return "Roles [id=" + id + ", roleName=" + roleName + ", users="
+ users + "]";
}
}
用户bean
public class Users {
private int id;
private String name;
public Users(){
}
public Users(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Users [id=" + id + ", name=" + name + "]";
}
}
配置
<bean id="roles" class="cn.com.ztz.spring.model.Roles">
<constructor-arg value="1"/>
<constructor-arg value="管理员"/>
<constructor-arg ref="users"/>
</bean>
<bean id="users" class="cn.com.ztz.spring.model.Users">
<constructor-arg value="2"/>
<constructor-arg value="张三"/>
</bean>
若要在Roles中引入Users,在Spring中就要用<constructor-arg ref=""/>指定资源
转载于:https://www.jianshu.com/p/a8e76e4bdfb4
上一篇: 第7章:优化 (来自mysql手册)
下一篇: Spring源码-Bean实例化