在gitee上看到最新的ControllerFactory代码中加入了依赖注入,Controller是每次请求都new一个实例的,每次new完实例还要进行service注入,可想而知性能会随着Controller中依赖数的增加而慢慢越差。
代码如下:
public Controller getController(Class<? extends Controller> controllerClass) throws ReflectiveOperationException { Controller ret = controllerClass.newInstance(); if (injectDependency) { com.jfinal.aop.Aop.inject(ret); } return ret; }
@JFinal 帮忙解惑上面问题
另外我想做一个单列的Controller(假设系统中的所有Controller都是无状态的),代码大致如下:
public class SingletonControllerFactory extends ControllerFactory{ private final static Map<Class<? extends Controller>, Controller> singletonCache = new ConcurrentHashMap<>(); public Controller getController(Class<? extends Controller> controllerClass) throws ReflectiveOperationException { Controller ret = singletonCache.get(controllerClass); if (ret == null) { ret = controllerClass.newInstance(); /** if (injectDependency) { com.jfinal.aop.Aop.inject(ret); }*/ singletonCache.put(controllerClass, ret); } return ret; } }
然后在配置文件中加入:
constants.setControllerFactory(new SingletonControllerFactory());
官方有个FastControllerFactory了,该有个SingletonControllerFactory吧?