Spring-Bean-配置bean-案例三:bean之间的依赖(只是改变创建顺序)

案例三:bean之间的依赖(只是改变创建顺序)

原来的创建顺序是按配置文件位置先后顺序创建的

(1)创建两个类

public class Employee {
    private String name;
    private Integer age;
    private Department dept;

    public Employee() {
        System.out.println("EMP被创建了");
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Department getDept() {
        return dept;
    }

    public void setDept(Department dept) {
        this.dept = dept;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", dept=" + dept +
                '}';
    }
}

 

public class Department {
    private String depaName;
    private Integer id;

    public Department() {
        System.out.println("DEPT被创建了");
    }

    public void setDepaName(String depaName) {
        this.depaName = depaName;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    @Override
    public String toString() {
        return "Department{" +
                "depaName='" + depaName + '\'' +
                ", id=" + id +
                '}';
    }
}

 

(2)配置文件

<bean id="dept" class="com.orz.spring.bean.Department">
    <property name="id" value="1"/>
    <property name="depaName" value="安保部"/>
</bean>
<bean id="employee" class="com.orz.spring.bean.Employee">
    <property name="name" value="李华"/>
    <property name="age" value="21"/>
    <property name="dept" ref="dept"/>
</bean>

(3)测试原来的创建顺序

@Test
public void test1()
{
    ApplicationContext applicationContext=new ClassPathXmlApplicationContext("bean.xml");
}

(4)结果

DEPT被创建了

EMP被创建了

 

(5)修改配置文件,加入depends-on属性

<bean id="dept" class="com.orz.spring.bean.Department" depends-on="employee">
    <property name="id" value="1"/>
    <property name="depaName" value="安保部"/>
</bean>
<bean id="employee" class="com.orz.spring.bean.Employee">
    <property name="name" value="李华"/>
    <property name="age" value="21"/>
    <property name="dept" ref="dept"/>
</bean>

 

(6)测试现在的创建顺序

(7)结果

EMP被创建了

DEPT被创建了

 

 
posted @ 2020-10-19 14:20  orz江小鱼  阅读(292)  评论(0编辑  收藏  举报