程序员社区

【Spring学习及总结12】基于xml的自动装配

文章目录

      • 1. autowire = "byName"
      • 2. autowire = "byType"
      • 3. autowire ="constructor"

首先看一下Person类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
    private String lastName;
    private Integer age;
    private String gender;
    private String email;
   
    private Car car;
}

可以注意到这个Person类里面有一个自定义类型的属性Car类:

@Data
public class Car {
    private String carName;
    private int price;
    private String color;
}

现在通过property标签手动为Person类里面自定义类型的属性赋值

<bean id="car" class="com.hh.pojo.Car">
    <property name="carName" value="宝马"/>
    <property name="color" value="黄色"/>
</bean>
<bean id="person" class="com.hh.pojo.Person" >
   <property name="car" ref="car"/>
</bean>

写一个测试类:

public class MyTest02 {
    //根据spring的配置文件得到ioc容器对象
    ClassPathXmlApplicationContext  context =
            new ClassPathXmlApplicationContext("spring2.xml");
    @Test
    public void test() {
        Person person = context.getBean("person", Person.class);
        System.out.println(person);
    }
}

在这里插入图片描述
那么现在来思考一个问题,如果不想手动赋值呢?
Spring为我们提供了autowire属性,该属性的取值有以下几种选择:

1. autowire = “byName”

以属性名car作为id去找Spring中配置的car对象
找不到,装配null
在这里插入图片描述

2. autowire = “byType”

以属性类型作为查找依据去Spring中找car对象
但是如果出现两个Car类型的对象,就会报错
找不到,装配null
在这里插入图片描述
在这里插入图片描述

3. autowire =“constructor”

先按照有参构造器的类型进行装配
如果找到多个相同类型的组件,就以参数名作为id继续装配
找不到,装配null
在这里插入图片描述

赞(0) 打赏
未经允许不得转载:IDEA激活码 » 【Spring学习及总结12】基于xml的自动装配

相关推荐

  • 暂无文章

一个分享Java & Python知识的社区