的关系

/ Spring / 没有评论 / 326浏览

我们知道IOC容器可以通过<bean>标签描述对象与对象之间的关系,并可以使用<ref>标签依赖另一个对象。实际上在<bean>标签与标签之间也具有某种关系,来满足我们开发时的需求。主要的关系有3种。它们分别是继承、依赖和引用。下面我们通过测试用例来演示它们3种关系的具体应用。

<bean id="user1" class="com.jilinwula.spring.User" p:username="admin" p:password="jilinwula" p:nickname="吉林乌拉" abstract="true"/>
<bean id="user2" p:username="guest" parent="user1"/>
@Test
public void test() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
User user = applicationContext.getBean("user2", User.class);
System.out.println(user);
}
User{username='guest', password='jilinwula', nickname='吉林乌拉'}

我们开发时,有时会有这种需求,就是希望某个类的初始化一定要赶在另一个类的初始化之前初始化。否则这个类可以完法完成工作。例如配置类初始化,一定要在业务类这前完成初始化动作的。如果我们有这种需求时,我们就可以用depends-on属性设置当前类的前置依赖。

<bean id="work" class="com.jilinwula.spring.Work" p:address="吉林乌拉"/>
<bean id="user" class="com.jilinwula.spring.User" depends-on="work"/>

如果这样设置我们可以保证work对象一定会在user对象之前完成初始化。

如果一个对象要依赖于另一个对象的id属性,我们可以通过下面的配置实现,目的就是将当前对象要依赖的对象的id保存到当前对象的属性中。

public class User {

private String username;
private String password;
private String nickname;
private String workId;
private Work work;

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getNickname() {
return nickname;
}

public void setNickname(String nickname) {
this.nickname = nickname;
}

public Work getWork() {
return work;
}

public void setWork(Work work) {
this.work = work;
}

public String getWorkId() {
return workId;
}

public void setWorkId(String workId) {
this.workId = workId;
}

@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", nickname='" + nickname + '\'' +
", workId='" + workId + '\'' +
", work=" + work +
'}';
}
}
<bean id="work" class="com.jilinwula.spring.Work" p:address="吉林乌拉"/>
<bean id="user" class="com.jilinwula.spring.User">
<property name="workId">
<idref bean="work"/>
</property>
</bean>
@Test
public void test() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
User user = applicationContext.getBean("user", User.class);
System.out.println(user);
}
User{username='null', password='null', nickname='null', workId='work', work=null}