byType
对该 bean 使用自动装配。dependency-check="objects"
属性值指定在这种情况下应该抛出错误。如果您使用
@Autowired
注解,则不需要提供autowire
属性。默认情况下,@Autowired
注释使用byType
自动装配。
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.leftso.autowire.byType.EmployeeBean" autowire="byType">
<property name="fullName" value="Lokesh Gupta"/>
</bean>
<bean id="department" class="com.leftso.autowire.byType.DepartmentBean" >
<property name="name" value="Human Resource" />
</bean>
</beans>
autowire="byType" 按类型自动装配
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;
}
}
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
是按类型成功注入的。https://www.leftso.com/article/995.html