Bean 的自动装配

时间:2020-05-13
本文章向大家介绍Bean 的自动装配,主要包括Bean 的自动装配使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Bean 的自动装配

自动装配是Spring满足bean依赖的一种方式

Spring会在上下文中自动寻找,并自动给bean装配属性

在Spring中有三种自动装配的方式

1.在xml中显示的配置

2.在java中显示配置

3.隐式的自动装配bean(重要)

​ 场景:一个人有两个宠物

实体类:

package com.liqiliang.pojo;
public class Dog {
        public void shot() {
            System.out.println("wang!");
        }
}
package com.liqiliang.pojo;
public class Cat {
    public void shot(){
        System.out.println("miao~");
    }
}
package com.liqiliang.pojo;

public class Person {

    private Cat cat;
    private Dog dog;
    private String name;

    @Override
    public String toString() {
        return "Person{" +
                "cat=" + cat +
                ", dog=" + dog +
                ", name='" + name + '\'' +
                '}';
    }

    public Cat getCat() {
        return cat;
    }

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

    public Dog getDog() {
        return dog;
    }

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

    public String getName() {
        return name;
    }

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

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 id="cat" class="com.liqiliang.pojo.Cat"/>
    <bean id="dog" class="com.liqiliang.pojo.Dog"/>

    <!--在xml中的显示配置-->
    <!--<bean id="person" class="com.liqiliang.pojo.Person">
        <property name="name" value="李启亮"/>
        <property name="cat" ref="cat"/>
        <property name="dog" ref="dog"/>
    </bean>-->

    <!--自动装配-->
    <!--
    byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的bean的id
    byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean(有弊端,万一出现两个同类型bean)
    -->
    <bean id="person" class="com.liqiliang.pojo.Person" autowire="byName">
        <property name="name" value="李启亮"/>

    </bean>
</beans>
小结:byName,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一直!
	byType,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致

测试类:

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

public class MyTest {

    @Test
    public void test01(){
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("bean.xml");
        Person person = (Person) applicationContext.getBean("person");
        person.getDog().shot();
        person.getCat().shot();
    }
}

原文地址:https://www.cnblogs.com/liqiliang1437/p/12881836.html