departmentBean
”属性(即它有一个 setDepartmentBean(..) 方法),容器将查找一个名为 的 bean 定义departmentBean
,如果找到,使用它来设置属性。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.xqlee" />
<bean id="employee" class="com.xqlee.demo.beans.EmployeeBean" autowire="byName">
<property name="fullName" value="Lokesh Gupta"/>
</bean>
<bean id="departmentBean" class="com.xqlee.demo.beans.DepartmentBean" >
<property name="name" value="Human Resource" />
</bean>
</beans>
在上面的配置中,我为“employee”bean 启用了按名称自动装配。它已使用使用 autowire="byName" 按名称自动装配依赖
autowire="byName"
.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;
}
}
public class DepartmentBean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
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());
}
}
Lokesh Gupta
Human Resource
http://blog.xqlee.com/article/996.html