Spring_基于xml自动装配

推荐视频:尚硅谷-Spring5框架最新版教程(idea版)
这是我觉得很不错的一套视频,我的spring系列的文章全是学习上述视频的学习笔记

基于xml自动装配

自动装配有两种类型:基于名称、基于类型

1 基于名称

autowride="byName"
是根据类中的属性名来进行装配的,也就是说,属性名和参照的id值要保持一致

1.1 基类

public class Employer {
    private Department dept;

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

    @Override
    public String toString() {
        return "Employer{" +
                "dept=" + dept +
                '}';
    }
}
public class Department {
    @Override
    public String toString() {
        return super.toString();
    }
}

1.2 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="employer" class="com.xtc.entity.Employer" autowire="byName" />
    <bean id="dept" class="com.xtc.entity.Department"/>
</beans>

1.3 测试类

public class EmployerTest {

    @Test
    public void test01(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean5.xml");
        Employer employer = context.getBean("employer", Employer.class);
        System.out.printf(employer.toString());
    }

}

2 基于类型

autowride="byType"
原理:根据类中属性的类型,在配置文件中找类型匹配的进行自动装配。但是,当有两个类型相同的bean时。会装配失败

2.1 配置文件

基类、测试类的代码可以沿用基于名称的

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="employer" class="com.xtc.entity.Employer" autowire="byType" />
    <bean id="dept" class="com.xtc.entity.Department"/>
</beans>

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值