首页 > 技术文章 > Spring-配置Bean-案例五:基于xml自动装配

orzjiangxiaoyu 2020-08-16 11:12 原文

案例五:基于xml自动装配

(实际开发中很少用)

我们把使用property标签赋值的方式叫做手动赋值。

 

自动装配(自动赋值),配置autowire进行自动装配

autowire="byName":以属性名作为id去容器中找到这个组件,给它赋值

autowire="byType":以属性类型作为查找的依据去容器中找到这个组件,给它赋值(只能同时存在一个同类型的bean

没有找到就装配null

 

例子:按属性类型自动装配

(1)创建两个类

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

    public Employee() {
    }

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

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

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

    public Department getDept() {
        return dept;
    }

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

    public Department() {
    }

    public String getDeptName() {
        return deptName;
    }

    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }

    @Override
    public String toString() {
        return "Department{" +
                "deptName='" + deptName + '\'' +
                '}';
    }
}

(2)配置文件

<bean id="dept" class="com.orz.spring.bean.Department">
    <property name="deptName" value="安全部"/>
</bean>
<bean id="emp" class="com.orz.spring.bean.Employee" autowire="byType" >
    <property name="name" value="李华"/>
    <property name="age" value="21"/>
</bean>

(3)测试

@Test
public void test1() {
    ConfigurableApplicationContext applicationContext=new ClassPathXmlApplicationContext("bean.xml");
    Employee emp = applicationContext.getBean("emp", Employee.class);
    System.out.println(emp);
}

(4)结果

Employee{name='李华', age=21, dept=Department{deptName='安全部'}}

 

例子:按name自动装配

(5)创建两个类

(6)配置文件

<bean id="dept" class="com.orz.spring.bean.Department">
    <property name="deptName" value="安全部"/>
</bean>
<bean id="emp" class="com.orz.spring.bean.Employee" autowire="byName" >
    <property name="name" value="李华"/>
    <property name="age" value="21"/>
</bean>

(7)测试

@Test
public void test1() {
    ConfigurableApplicationContext applicationContext=new ClassPathXmlApplicationContext("bean.xml");
    Employee emp = applicationContext.getBean("emp", Employee.class);
    System.out.println(emp);
}

(8)结果

Employee{name='李华', age=21, dept=Department{deptName='安全部'}}

推荐阅读