学习笔记 之 @Inject

今日闲暇,阅读文档 Inject注入,文档简洁明了。然感兴趣于所描述特别注意之“使用 Inject 注入的前提是使用 @Inject 注解的类的对象的创建是由jfinal接管的”,以controller为入口,查看了其源代码,以此笔记:

我们知道从JFinal顶层框架图得知,有关键的ActionHandler,在这创建了controller对象,如下

  1. public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
  2.     
  3.     Controller controller = null;
  4.     try { 
  5.         controller = controllerFactory.getController(action.getControllerClass());
  6.         controller._init_(action, request, response, urlPara[0]);
  7.     }
  8. }

继续查看 controllerFactory

  1. public Controller getController(Class<? extends Controller> controllerClass) throws ReflectiveOperationException {
  2.     Controller ret = controllerClass.newInstance();
  3.     if (injectDependency) {
  4.        com.jfinal.aop.Aop.inject(ret);
  5.     }
  6.     return ret;
  7. }

可以看到,如果我们JFinalConfig 中配置了依赖注入就可以在controller中使用@Inject了

  1. public void configConstant(Constants me) {
  2.     me.setInjectDependency(true);
  3. }

具体注入的关键方法如下

  1. protected void doInject(Class<?> targetClass, Object targetObject) throws ReflectiveOperationException {
  2.  
  3.     Field[] fields = targetClass.getDeclaredFields();
  4.     if (fields.length != 0) {
  5.        for (Field field : fields) {
  6.           Inject inject = field.getAnnotation(Inject.class);
  7.           if (inject == null) {
  8.              continue ;
  9.           }
  10.  
  11.           Class<?> fieldInjectedClass = inject.value();
  12.           if (fieldInjectedClass == Void.class) {
  13.              fieldInjectedClass = field.getType();
  14.           }
  15.  
  16.           Object fieldInjectedObject = doGet(fieldInjectedClass);
  17.           field.setAccessible(true);
  18.           field.set(targetObject, fieldInjectedObject);
  19.        }
  20.     }
  21.  
  22. }


评论区

热门分享

扫码入社