1.SpringDI介绍
DI(Dependency Injection)依赖注入 。相对于IoC而言,依赖注入(DI)更加准确地描述了IoC的设计理念。所谓依赖注入,即组件之间的依赖关系由容器在应用系统运行期来决定,也就是由容器动态地将某种依赖关系的目标对象实例注入到应用系统中的各个关联的组件之中。
2.模拟SpringDI的步骤
- 我们要准备两个类Student和Teacher,将Teacher中的资源注入到Student中,那么Student就可以调用Teacher中的资源
- 自定义注解@MyAutowired,用于将Teacher中的资源注入到Student中
- 准备Student类
- 准备Teacher类
- 测试我们模拟的DI
3.自定义注解@MyAutowired
package cn.tedu.designdi;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAutowired {
String value() default "" ;
}
4.创建Student类
@Component
public class Student {
private String name="王一博";
@MyAutowired //di
private Teacher teacher;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", teacher=" + teacher +
'}';
}
}
5.创建Teacher类
package cn.tedu.designdi;
import org.springframework.stereotype.Component;
@Component
public class Teacher {
private String name="张老三";
@Override
public String toString() {
return "Teacher{" +
"name='" + name + '\'' +
'}';
}
}
6.测试模拟DI
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.lang.reflect.Field;
//有注解的属性就new
public class TestDI {
@Test
public void di() throws Exception{
//获取Student类里的属性,哪个属性有MyAutowired注解就给他new一个
Class s = Class.forName("cn.tedu.designdi.Student");
Object o = s.newInstance();
Field[] fs = s.getDeclaredFields();
for (Field f : fs) {
MyAutowired an = f.getAnnotation(MyAutowired.class);
if(an != null){
f.setAccessible(true);
f.set(o,new Teacher());
}
}
// Student{name='王一博', teacher=Teacher{name='张老三'}}
System.out.println((Student)o);
}
}