【发布时间】:2015-01-24 06:04:49
【问题描述】:
我尝试在春季了解 DI。我应该在哪里使用带有 context.getBean 的对象以及在哪里使用 @inject 注释?
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 得到了 person 和 address 对象,我也可以用 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>
【问题讨论】:
-
首先:看一下Spring Boot。它为您处理大部分样板配置。您几乎不需要明确使用
getBean;我想我从来没有真正的代码。
标签: java spring dependency-injection annotations inject