我试着在春天理解DI。我应该在哪里使用context.getBean的对象以及@inject anntotation的位置?
public class App {
public static void main(String[] args) {
new Controller().iniController();
}
}
public class Controller {
public void iniController() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("com/beans/beans.xml");
Address address = context.getBean("address", Address.class);
Person person = context.getBean("person", Person.class);
Employee employee = context.getBean("employee", Employee.class);
address.setCity("my city");
person.setName("my name");
System.out.println(employee);
context.close();
}
}
使用context.getBean方法获取地址,人员和员工对象是否正确?
@Component
public class Employee {
@Inject
private Person person;
@Inject
private Address address;
@Override
public String toString() {
return "Employee: "+ person.getName() +" from "+ address.getCity();
}
}
在这里,我使用Inject获取了人物和地址对象,我还可以使用getBean方法获取这些对象吗?
@Component
public class Address {
private String city;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
@Component
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
<?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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.model"></context:component-scan>
</beans>
答案 0 :(得分:0)
你应该总是更喜欢依赖注入,而不是getBean,或者我应该说完全避免使用getBean。
依赖注入非常有效地关联松散耦合的组件以及配置这些组件。特别是如果组件之间的关联在组件的整个生命周期中持续存在。
更具体地说,依赖注入在这些情况下是有效的:
定义DI可以帮助您轻松更改底层实现,而无需担心使用此实现的人员。
如果这一切仍让你感到困惑,你可以在google上找到使用DI的几十个理由