Spring中关于xml自动装配

前言:自动装配是指根据指定装配规则(属性名称或者属性类型),Spring自动将匹配的属性值进行注入

自动装配的过程

bean 标签属性 autowire,配置自动装配 autowire 属性常用两个值:

  • byName 根据属性名称注入 ,注入值 bean 的 id 值和类属性名称一样
  • byType 根据属性类型注入

1.根据属性名称自动注入

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="person" class="iocbean.byxml.automatic.Person">
        <property name="name" value="小明"></property>
    </bean>

    <bean id="student" class="iocbean.byxml.automatic.Student" autowire="byName">
        <!--有了autowire="byName" 之后就不需要手动注入了
            注入值 bean 的 id 值和类属性名称一样即可-->
        <!--<property name="person" ref="person"></property>-->
    </bean>
</beans>

Person类:

public class Person {
    
    
    public String name;

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

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

Student类:

public class Student {
    
    
    private Person person;
    private Person person1;

    public void setPerson(Person person) {
    
    
        this.person = person;
    }

    public void setPerson1(Person person1) {
    
    
        this.person1 = person1;
    }

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

测试类:

public class DemoTest {
    
    
    @Test
    public void test1(){
    
    
        ApplicationContext context = new ClassPathXmlApplicationContext("iocbean/byxml/automatic/bean.xml");

        Student student = context.getBean("student", Student.class);

        System.out.println(student);
    }
}

输出结果:

Student{person=Person{name='小明'}, person1=null}

Process finished with exit code 0


2.根据属性类型自动注入

<bean id="student1" class="iocbean.byxml.automatic.Student" autowire="byType">
    <!--有了autowire="byType" 之后就不需要手动注入了
        所有同类型的属性都将被注入一样的值-->
    <!--<property name="person" ref="person"></property>-->
</bean>

测试类:

public class DemoTest {
    
    
    @Test
    public void test1(){
    
    
        ApplicationContext context = new ClassPathXmlApplicationContext("iocbean/byxml/automatic/bean.xml");

        Student student1 = context.getBean("student1", Student.class);

        System.out.println(student1);
    }
}

输出结果:

Student{person=Person{name='小明'}, person1=Person{name='小明'}}

Process finished with exit code 0

可以看到
byName 根据属性名称注入 ,注入值 bean 的 id 值和类属性名称一样才可以注入,所以person有值,person1为null
而byType 根据属性类型注入只需要类属性的类型一样就可以注入,person、person1的类型都为Person,所以都有值。

猜你喜欢

转载自blog.csdn.net/MrYushiwen/article/details/110951267