HK2框架的简单自实现kunJ
kunJ
kunJ框架,是基于HK2框架的一个自实现注入框架,功能比较简单,重在探索依赖注入的实现原理。
实现细节
- 自定义3个注解,Access,Inject,Service
- 在Service中实现对Inject对象的注入(Inject对象必须是Service且有默认构造器)
- 在Service中自动调用标注了Access的方法
- 注入实现类ClassAnalyzer中reInject,实现动态自定义注入(覆盖自动注入)
整体架构
示例
//Sevice
@Service
public class ClassOfArt implements Class{
@Override
public void hi() {
System.out.println("this is class of art.");
}
}
//Sevice
@Service
public class College {
@Inject
private Department art;
@Access
public void run() {
System.out.println("this is college of art.");
art.hi();
}
}
//Sevice
@Service
public class DepartmentOfArt implements Department{
@Inject
private Class artClass;
@Override
public void hi() {
System.out.println("this is department of Art.");
artClass.hi();
}
}
//College需要注入Department,Department需要注入Class
//注入
try {
ClassAnalyzer.inject();
} catch (Exception e) {
e.printStackTrace();
}
结果:
//自定义注入
Class art = new Class() {
@Override
public void hi() {
System.out.println("hello world");
}
};
try {
ClassAnalyzer.reInject(Class.class, art);
} catch (Exception e) {
e.printStackTrace();
}
运行结果:
github地址
I am a slow walker, but I never walk backwards.