【Spring】bean的自动装配

目录

一.byName

二.byType

快捷书写


people1

package org.example;

public class People1 {
    public void eat(){
        System.out.println("吃饭");
    }
}

people2

package org.example;

public class People2 {
    public void sleep(){
        System.out.println("睡觉");
    }
}

person

package org.example;

public class Person {
    private People1 people1;
    private People2 people2;

    public People1 getPeople1() {
        return people1;
    }

    public void setPeople1(People1 people1) {
        this.people1 = people1;
    }

    public People2 getPeople2() {
        return people2;
    }

    public void setPeople2(People2 people2) {
        this.people2 = people2;
    }

    @Override
    public String toString() {
        return "person{" +
                "people1=" + people1 +
                ", people2=" + people2 +
                '}';
    }
}

一.byName

自动在容器上下文查找与set方法后面的值对应的bean id

(理解:

例如针对people1来讲

将People1这个字符串的首字母小写得到people1

然后去spring的容器里查找与people1相同beanid

 如果找不到则报空指针异常(也就是名称要保证全局唯一)

<?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="people1" class="org.example.People1"/>
    <bean id="people2" class="org.example.People2 "/>

    <bean id="person" class="org.example.Person" autowire="byName">

    </bean>

</beans>

 测试

package org.example;

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

public class Test8 {
    public static void main(String[] args) {
       ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
       Person person= context.getBean("person",Person.class);
       person.getPeople1().eat();
       person.getPeople2().sleep();
    }
}

二.byType

自动在容器上下文查找与自己对象属性相同的bean

使用byType仍然可以得到如上测试的结果 

但是要保证自己对象的属性类型要全局唯一

使用byType可以省略id的书写

    <bean  class="org.example.People1"/>
    <bean  class="org.example.People2 "/>

    <bean id="person" class="org.example.Person" autowire="byType">

快捷书写

new ClassPathXmlApplicationContext

点回车 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值