3、spring的五种自动装配方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AustinBoris/article/details/55522529

spring的五种自动装配方式

  • no —— 默认情况,自动装配方式为手动装配,即通过ref手动设定
  • byName —— 根据属性名称自动装配,如果一个bean的名称和其他bean属性一致,则进行自动装配
  • byType——按照数据类型进行自动装配,如果一个bean的名称和其他bean的属性的数据类型一致,则进行兼容并自动装配
  • constructor ——通过构造函数参数的byType方式。
  • autodetect —— 如果找到默认的构造函数,使用“自动装配用构造”; 否则,使用“按类型自动装配”。

在演示五种装配方式时,需要构建两个辅助类

Customer.java

public class Customer {
    private Address address;
    public Customer(Address address){
        this.address = address;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
}

Address.java

public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

1、no 默认装配方式

  <!-- 默认自动装配方式为no时,手动装配bean -->
  <bean id="customer" 
        class="com.main.autowrite.defaul.Customer">
        <property name="address" ref="address"></property>
  </bean>
  <bean id="address" class="com.main.autowrite.defaul.Address"></bean>

2、byName 方式自动装配

  <!-- byName自动装配方式 -->
  <bean id="customer" 
        class="com.main.autowrite.byname.Customer" 
        autowire="byName">
  </bean>
  <bean 
      id="address" 
      class="com.main.autowrite.byname.Address">
      <property name="address" value="Block A 888, CA" />
  </bean>

3、byType方式自动装配

  <!-- byType自动装配方式 -->
  <bean id="customer" 
        class="com.main.autowrite.bytype.Customer" 
        autowire="byType">
  </bean>
  <bean id="address" class="com.main.autowrite.bytype.Address">
    <property name="address" value="Block A 888, CA" />
</bean>

4、constructor方式自动装配

  <!-- constructor自动装配方式 -->
  <bean id="customer" 
        class="com.main.autowrite.constructor.Customer" 
        autowire="constructor">
  </bean>
  <bean id="address" class="com.main.autowrite.constructor.Address">
    <property name="address" value="Block A 888, CA" />
</bean>

5、autodetect方式自动装配

说明:auto-wire’ 和 ‘dependency-check’ 相结合,以确保属性始终自动装配成功。

  <!-- autodetect自动装配方式 -->
  <bean id="customer" 
        class="com.main.autowrite.autodetect.Customer" 
        autowire="autodetect">
  </bean>
  <bean id="address" class="com.main.autowrite.autodetect.Address">
    <property name="address" value="Block A 888, CA" />
</bean>

测试方法:
说明:以上五种装配方式均可用以下方式来进行验证,套路是一样的
这里用byName方式来演示

    @Test
    public void test(){

        ApplicationContext context = 
                new ClassPathXmlApplicationContext("com/main/autowrite/byname/custom.xml");

        Customer customer = (Customer)context.getBean("customer");

        System.out.println(customer.getAddress().getAddress());
    }

运行结果为:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/AustinBoris/article/details/55522529
今日推荐