spring的学习日记-spring-的自动装配bean1-xml的装配方式

Spring的自动装配,基于xml的方式,使用byName或者byType的方式

在bean中我们使用自动装配,有2种方式:byName或者byType

byName的方式:使用该方式,我们的id属性的值必需和实体类中set方法的后面的名字相同

byType的方式:使用该方式,我们注册bean的时候,相同类型的bean只能注册一个可以省略id属性的值

 

pojo层:

package com.fu.pojo;

public class People {
    private Dog dog;
    private Cat cat;

    public People(Dog dog, Cat cat) {
        this.dog = dog;
        this.cat = cat;
        System.out.println("我是有参构造创建的方式");
    }

    public People() {
        System.out.println("我是无参构造创建的方式");
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
        System.out.println("set赋值方式");
    }

    public Cat getCat() {
        return cat;
    }

    public void setCat(Cat cat) {
        this.cat = cat;
        System.out.println("set赋值方式");
    }

    @Override
    public String toString() {
        return "People{" +
                "dog=" + dog +
                ", cat=" + cat +
                '}';
    }
}
package com.fu.pojo;

public class Dog {
    public void shout(){
        System.out.println("我是狗");
    }

}
package com.fu.pojo;

public class Cat {
    public void shout(){
        System.out.println("我是猫");
    }

}

spring的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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

<!--    注册bean-->
    <bean id="dog" class="com.fu.pojo.Dog"/>
    <bean id="cat" class="com.fu.pojo.Cat"/>

<!--    <bean id="people" class="com.fu.pojo.People" autowire="byName"/>-->
    
    <bean id="people" class="com.fu.pojo.People" autowire="byType"/>

</beans>

测试类:

import com.fu.pojo.People;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/*  Bean的自动装配:byType方式,使用通过类型的方式进行匹配,在xml中我们只能注册一个类同类型的bean,不能注册多个
                  byName方式,通过id的属性值进行匹配,该id的值必需和实体类中set方法后面的值相同
 */
public class MyTest {

    public static void main(String[] args) {
        //获取IOC容器
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        //有了容器,我们就get到what
        People people = context.getBean("people", People.class);

        people.getCat().shout();
        people.getDog().shout();
    }
}

测试结果:

 

posted @ 2022-03-04 18:59  Fu_Zhang  阅读(65)  评论(0)    收藏  举报