spring bean的自动装配

两种方式

byName:自动查找容器上下文,set方法名 与 bean id 名相同

byType: 自动查找容器上下文, class名称与类名相同

案例

人有猫和狗

1、pojo

cat.java

package com.wt.pojo;

public class Cat {
    public void shout(){
        System.out.println("mao~");
    }
}

mao.java

package com.wt.pojo;

public class Dog {
    public void shout(){
        System.out.println("wang~");
    }
}

person.java

package com.wt.pojo;


public class Person {
    private String name;
    private Dog dog;
    private Cat cat;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    public Cat getCat() {
        return cat;
    }

    public void setCat(Cat cat) {
        this.cat = cat;
    }
}

2、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 id="cat" class="com.wt.pojo.Cat"/>
<bean id="dog" class="com.wt.pojo.Dog"/>
<!--byName方法 自动在容器上下文中查找 set后面的名字 与 id 相同-->
<bean id="per2" class="com.wt.pojo.Person" scope="singleton" autowire="byName" name="person2">
    <property name="name" value="tom"/>
</bean>
    
<!--byType方法 自动查询容器中 class名称与实现类 相同的类-->
    <bean id="person" class="com.wt.pojo.Person" scope="singleton" autowire="byType" name="per">
        <property name="name" value="tom"/>
    </bean>

</beans>

3、测试

import com.wt.pojo.Person;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {

    @Test
    public void getPerson(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Person person = context.getBean("per", Person.class);
        System.out.println(person.getName());
        person.getCat().shout();
        person.getDog().shout();
    }
}
原文地址:https://www.cnblogs.com/wt7018/p/13337882.html