spring-210727-01--IOC容器--Bean管理xml方式-自动装配

spring-210727-01–IOC容器–Bean管理xml方式-自动装配


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

演示

Emp.java

package com.bgy.autowire;

public class Emp {
    private Dept dept;

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

    @Override
    public String toString() {
        return "Emp{" +
                "dept=" + dept +
                '}';
    }
}

Dept.java

package com.bgy.autowire;

public class Dept {
}

autowiretest.xml(笔记在这儿哦)

<?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方式 -->
    <bean id="emp01" class="com.bgy.autowire.Emp">
        <property name="dept" ref="dept"></property>
    </bean>

    <!--
        自动装配:
            bean标签中,属性autowire来实现自动装配

            autowire:
                byName:
                    根据属性名称注入,注入bean的id值和类属性名称必须一样,
                    即id="dept" 必须和Emp类中的Dept的属性名称一样。
                byType:
                    根据属性类型注入。
                    要保证只有一个配置文件中只有一个对象类型,否则它不知道注入那个,就会报错。
    -->
    <bean id="emp02" class="com.bgy.autowire.Emp" autowire="byName">
    </bean>

    <!-- 自动装配也需要弄出来一个这个对象 -->
    <bean id="dept" class="com.bgy.autowire.Dept"></bean>
</beans>

TestAutowire.java

import com.bgy.autowire.Emp;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestAutowire {

    /**
     * 外部bean方式
     */
    @Test
    public void test01(){
        // 1. 加载spring配合文件
        ApplicationContext context = new ClassPathXmlApplicationContext("autowiretest.xml");
        // 2. 通过配置文件创建对象
        // 外部bean方式
        Emp emp01 = context.getBean("emp01", Emp.class);
        System.out.println(emp01);
    }

    /**
     * 自动装配
     */
    @Test
    public void test02(){
        // 1. 加载spring配合文件
        ApplicationContext context = new ClassPathXmlApplicationContext("autowiretest.xml");
        // 2. 通过配置文件创建对象
        // 外部bean方式
        Emp emp02 = context.getBean("emp02", Emp.class);
        System.out.println(emp02);
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值