IOC操作Bean管理--基于XML(自动装配)

IOC操作Bean管理2(基于XML)

XML自动装配

概念

根据指定的装配规则(属性名称或者属性类型),Spring自动将匹配的属性值进行注入

bean标签属性autowire有两个值:

  • byName:根据属性名注入,这里id的名字要和属性的名字一样,否则找不到
  • byType:根据属性类型注入
代码实例
<?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="emp" class="com.bean.BeanAutoWire.Emp" autowire="byName">
    <!--实现自动装配根据类型注入-->
    <!--<bean id="emp" class="com.bean.BeanAutoWire.Emp" autowire="byType">-->
        <!--手动装配:<property name="dept" ref="dept"/>-->
    </bean>

    <bean id="dept" class="com.bean.BeanAutoWire.Dept">

    </bean>
</beans>
package com.bean.BeanAutoWire;

public class Dept {
    @Override
    public String toString() {
        return "Dept{}";
    }
}
package com.bean.BeanAutoWire;

public class Emp {

    public Dept dept;

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

    @Override
    public String toString() {
        return "Emp{" +
                "dept=" + dept +
                '}';
    }
}
package com.bean.BeanAutoWire;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanAutoWire {
    public static void main(String args[]) {
        //加载spring配置文件
        ApplicationContext content =
                new ClassPathXmlApplicationContext("BeanAutoWire.xml");
        //获取配置文件创建的对象
        Emp emp = content.getBean("emp",Emp.class);
        System.out.println(emp);
        System.out.println(emp.dept.toString());
    }
}

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值