Spring ~spring 自动装配

显式装配

  • cat
package com.guo.pojo;

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

  • dog
package com.guo.pojo;

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

  • people
package com.guo.pojo;

public class People {
    
    
    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;
    }

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


  • beans.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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">


    <bean id="cat" class="com.guo.pojo.Cat"/>
    <bean id="dog" class="com.guo.pojo.Dog"/>

    <!--显式装配-->
    <bean id="people" class="com.guo.pojo.People">
        <property name="name" value="显式装配"/>
        <property name="cat" ref="cat"/>
        <property name="dog" ref="dog"/>
    </bean>

    
</beans>
  • 测试
@Test
    public  void testAutoWired(){
    
    
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        People people = context.getBean("people", People.class);
        people.getCat().shout();
        people.getDog().shout();

    }

自动装配

byName

  • 通过名字实现自动装配
  • autowire=“byName”
  • 需要在 beans.xml 中 先配置好相关对象
  • 依赖beanid
<!--
    自动装配
    byName:自动寻找容器上下文中和自己对象的set方法后面的值对应的beanid
-->
<bean id="people" class="com.guo.pojo.People" autowire="byName">
    <property name="name" value="隐式装配"/>
</bean>

byType

  • 通过类型实现装配
  • autowire=“byType”
  • 需要在 beans.xml 中 先配置好相关对象
  • 依赖bean类型
<!--
    自动装配
    byType:自动寻找容器上下文中和自己对象的属性类型相同的beanid
-->
<bean id="people" class="com.guo.pojo.People" autowire="byType">
    <property name="name" value="隐式装配"/>
</bean>

byName 和 byType 的缺点

自动装配
    byName:依赖bean的id名
    需要保证bean的id唯一,且和set方法的值保持一致

    byType:依赖bean的Class类型
    需要保证bean的Class唯一,且和注入的类型保持一致

Guess you like

Origin blog.csdn.net/m0_47585722/article/details/120253115