今日闲暇,阅读文档 Inject注入,文档简洁明了。然感兴趣于所描述特别注意之“使用 Inject 注入的前提是使用 @Inject 注解的类的对象的创建是由jfinal接管的”,以controller为入口,查看了其源代码,以此笔记:
我们知道从JFinal顶层框架图得知,有关键的ActionHandler,在这创建了controller对象,如下
public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
Controller controller = null;
try {
controller = controllerFactory.getController(action.getControllerClass());
controller._init_(action, request, response, urlPara[0]);
}
}继续查看 controllerFactory
public Controller getController(Class<? extends Controller> controllerClass) throws ReflectiveOperationException {
Controller ret = controllerClass.newInstance();
if (injectDependency) {
com.jfinal.aop.Aop.inject(ret);
}
return ret;
}可以看到,如果我们JFinalConfig 中配置了依赖注入就可以在controller中使用@Inject了
public void configConstant(Constants me) {
me.setInjectDependency(true);
}具体注入的关键方法如下
protected void doInject(Class<?> targetClass, Object targetObject) throws ReflectiveOperationException {
Field[] fields = targetClass.getDeclaredFields();
if (fields.length != 0) {
for (Field field : fields) {
Inject inject = field.getAnnotation(Inject.class);
if (inject == null) {
continue ;
}
Class<?> fieldInjectedClass = inject.value();
if (fieldInjectedClass == Void.class) {
fieldInjectedClass = field.getType();
}
Object fieldInjectedObject = doGet(fieldInjectedClass);
field.setAccessible(true);
field.set(targetObject, fieldInjectedObject);
}
}
}