Spring5核心原理-bean 按类型自动装配

Spring5核心原理-bean 按类型自动装配

  1. 如果容器中只有一个属性类型的 bean。
  2. 如果有多个,则会抛出一个致命异常,这表明您可能不会byType对该 bean 使用自动装配。
  3. 如果没有匹配的 bean,则什么也不会发生;该属性未设置。如果这是不可取的,设置dependency-check="objects"属性值指定在这种情况下应该抛出错误。

如果您使用@Autowired注解,则不需要提供autowire属性。默认情况下,@Autowired注释使用byType自动装配。

按类型自动装配 Bean

在上下文文件中定义 Bean

一个典型的 bean 配置文件(例如
applicationContext.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
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context/
  http://www.springframework.org/schema/context/spring-context-3.0.xsd">
     
  <bean id="employee" class="com.note234.autowire.byType.EmployeeBean" autowire="byType">
    <property name="fullName" value="Lokesh Gupta"/> 
  </bean>
  
  <bean id="department" class="com.note234.autowire.byType.DepartmentBean" >
    <property name="name" value="Human Resource" />
  </bean>
 
</beans>

 autowire=”byType” 按类型自动装配

Bean classes

在上面的配置中,我为 ‘ 
employee‘ bean 启用了按类型自动装配。它已使用
autowire="byType"
employee现在bean中的所有属性(例如 )都将使用自动装配
departmentBean进行查找。
byType

 

import org.springframework.beans.factory.annotation.Autowired;
 
public class EmployeeBean
{
  private DepartmentBean departmentBean;
   
  private String fullName;
 
  public DepartmentBean getDepartmentBean() {
    return departmentBean;
  }
  public void setDepartmentBean(DepartmentBean departmentBean) {
    this.departmentBean = departmentBean;
  }
  public String getFullName() {
    return fullName;
  }
  public void setFullName(String fullName) {
    this.fullName = fullName;
  }
}


DepartmentBean看起来像这样:

public class DepartmentBean{
  private String name;
 
  public String getName() {
    return name;
  }
 
  public void setName(String name) {
    this.name = name;
  }
}

测试依赖

要测试该 bean 是否已正确设置,请运行以下代码:

 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class TestAutowire {
  public static void main(String[] args) {
    ApplicationContext context = 
            new ClassPathXmlApplicationContext(new String[] {"com/howtodoinjava/autowire/byType/applicationContext.xml"});
      
          EmployeeBean employee = (EmployeeBean)context.getBean("employee");
 
          System.out.println(employee.getFullName());
 
          System.out.println(employee.getDepartmentBean().getName());
  }
}

Output:

Lokesh Gupta
Human Resource

显然,依赖项
departmentBean是按类型成功注入的。

 

Spring5核心原理-bean 按类型自动装配

相关文章:

你感兴趣的文章:

标签云: