【发布时间】:2016-03-03 18:33:49
【问题描述】:
在我的 spring 示例中,我使用以下 XML 配置文件声明了两个 bean。
EmployeeBean.java
package autowire;
import org.springframework.beans.factory.annotation.Autowired;
public class EmployeeBean {
private String fullName;
@Autowired
private DepartmentBean departmentBean;
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public DepartmentBean getDepartmentBean() {
return departmentBean;
}
}
DepartmentBean.java
package autowire;
public class DepartmentBean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
spring-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<context:annotation-config />
<bean id="employee" class="autowire.EmployeeBean" autowire="byType">
<property name="fullName" value="Charith"></property>
</bean>
<bean id="deptment" class="autowire.DepartmentBean">
<property name="name" value="IT Department"></property>
</bean>
</beans>
TestAutowire .java
package autowire;
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[] {"spring-servlet.xml"});
EmployeeBean employee = (EmployeeBean)context.getBean("employee");
System.out.println(employee.getFullName());
System.out.println(employee.getDepartmentBean().getName());
}
}
上面的例子很好。之后我删除了'@Autowired'注释并将以下行添加到EmployeeBean.java
public void setDepartmentBean(DepartmentBean departmentBean) {
this.departmentBean = departmentBean;
}
现在示例在相同的输出下工作正常。我的问题是,使用“@Autowired”注释时的实际好处是什么?因为代码在没有注释但使用 setter 方法时也能正常工作。请帮助我。
【问题讨论】:
标签: java spring spring-mvc annotations autowired