JFinal 的Controller自动注册工具AutoControllerRegist

首先上如何使用的代码

public void configRoute(Routes me) {

		AutoControllerRegist.regist(me);

		//me.add("/mobileBind", MobileBindController.class);

	}

如果不用AutoControllerRegist我们需要打开那行注释.

AutoControllerRegist的注册规则探测到所有继承了Controller的类,然后查找类上是否有ControllerBind注解,有注解按照注解配置的值进行注册.如果没有则检测类名是否用Controller作为结尾,如果不是则跑出异常,是则截取类名中Controller前面的部分并且首字母小写作为controllerkey。

 


 

 

package com.jfinal.ext.route;

import java.util.List;

import com.jfinal.config.Routes;
import com.jfinal.core.Controller;
import com.jfinal.plugin.tablebind.ClassSearcher;
import com.jfinal.util.StringKit;

public class AutoControllerRegist {

	@SuppressWarnings("rawtypes")
	public static void regist(Routes routes) {
		List<Class> classList = ClassSearcher.findClasses(Controller.class);
		ControllerBind controllerBind = null;
		for (Class clazz : classList) {
			controllerBind = (ControllerBind) clazz.getAnnotation(ControllerBind.class);
			if (controllerBind == null) {
				routes.add(controllerKey(clazz), clazz);
			} else {
				routes.add(controllerBind.controllerKey(), clazz, controllerBind.viewPath());
			}
		}
	}

	private static String controllerKey(Class clazz) {
		if (!clazz.getSimpleName().endsWith("Controller")) {
			throw new RuntimeException(clazz + " don,t has a ControllerBind annotation and it,s don,t end Controller! ");
		}
		String controllerKey = "/" + StringKit.firstCharToLowerCase(clazz.getSimpleName());
		controllerKey = controllerKey.substring(0, controllerKey.indexOf("Controller"));
		return controllerKey;
	}
}

package com.jfinal.ext.route;

public @interface  ControllerBind {
	public String controllerKey() ;
	public String viewPath() default"";
} 

ClassSearcher类见另一篇自动注册Model的博客 http://my.oschina.net/b1412/blog/68083

你可能感兴趣的:(java,jFinal,极速开发)