Spring核心原理-bean 按名称自动装配

Spring核心原理-bean 按名称自动装配

例如,如果您有一个按名称设置为自动装配的 bean 定义,并且它包含一个“ 
departmentBean”属性(即它有一个 setDepartmentBean(..) 方法),容器将查找一个名为 的 bean 定义
departmentBean,如果找到,使用它来设置属性。

 

按名称自动装配示例

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">
 
    <context:component-scan base-package="com.note234" />    
     
   <bean id="employee" class="com.note234.demo.beans.EmployeeBean" autowire="byName">
        <property name="fullName" value="Lokesh Gupta"/>
    </bean>
   
    <bean id="departmentBean" class="com.note234.demo.beans.DepartmentBean" >
        <property name="name" value="Human Resource" />
    </bean>
     
</beans>

 

使用 autowire=”byName” 按名称自动装配依赖

在上面的配置中,我为“employee”bean 启用了按名称自动装配。它已使用
autowire="byName".

EmployeeBean.java:

public class EmployeeBean
{
    private String fullName;
      
    private DepartmentBean departmentBean;
  
    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.java :

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;
 
import com.howtodoinjava.demo.beans.EmployeeBean;
 
public class TestAutowire  {
  public static void main(String[] args) {
 
        ApplicationContext context =
                  new ClassPathXmlApplicationContext(new String[] {"application-context.xml"});
           
        EmployeeBean employee = (EmployeeBean) context.getBean ("employee");
 
        System.out.println(employee.getFullName());
 
        System.out.println(employee.getDepartmentBean().getName());
    }
}
 

Output:

Lokesh Gupta
Human Resource

显然,依赖项是按名称成功注入的。

 

Spring核心原理-bean 按名称自动装配

相关文章:

你感兴趣的文章:

标签云: