更多 Java 高级知识方面的文章,请参见文集《Java 高级知识》
控制反转 IOC 依赖注入 DI
控制反转 IOC:利用了反射机制
依赖注入 DI:是 IOC 的一种形式,使类与类之间解耦合
示例:
User Bean 实体类 Student:
- 提供默认的构造方法
- 提供 set/get 方法
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public void print() {
System.out.println(name + "-" + age);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
XML 配置文件 student.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="studentBean" class="Student">
<property name="name" value="Tom"/>
<property name="age" value="18"/>
</bean>
</beans>
通过 BeanFactory 来注入 User Bean:
public static void main(String[] args) throws Exception {
BeanFactory bf = new ClassPathXmlApplicationContext("student.xml");
Student studentBean = (Student) bf.getBean("studentBean");
studentBean.print();
}