在 Spring 框架中,按名称自动装配 bean 允许对属性进行自动装配,这样它将检查容器并查找名称与需要自动装配的属性完全相同的 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.leftso" />
<bean id="employee" class="com.leftso.demo.beans.EmployeeBean" autowire="byName">
<property name="fullName" value="Lokesh Gupta"/>
</bean>
<bean id="departmentBean" class="com.leftso.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
显然,依赖项是按名称成功注入的。
原创文章,作者:端木书台,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/243955.html