JFinal 自动探测Model 注册插件 AutoScanPlugin(一)

2014-11-24 08:51:32 · 作者: · 浏览: 5

在ssh等框架中有不少自动扫包注册的功能,当我们类较多的时候可以减少不少的工作。
根据这个思路写了个简单的自动扫包注册Model的插件。
扫描classes下面所以继承了Model的类注册到ActiveRecordPlugin中。数据库表名默认采用骆峰。
比如MobileBind.Java则映射到mobieBind表.另外也可以选择全部大写和全部小写的策略.


01
/**
02
* 配置插件
03
*/
04
public void configPlugin(Plugins me) {
05
DruidPlugin druidPlugin = new DruidPlugin.DruidBuilder(getProperty("url"), getProperty("username"),
06
getProperty("password")).build();
07
me.add(druidPlugin);
08
ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin);
09
arp.setShowSql(true);
10
SqlReporter.setLogger(true);
11
AutoScanPlugin autoScanPligin = new AutoScanPlugin(arp,TableNameStyle.LOWER);
12
me.add(autoScanPligin); //自动扫包注册model插件要在ActiveRecordPlugin之前注册
13
me.add(arp);
14
}

01
package com.jfinal.plugin.autoscan;
02
import java.io.File;
03
import java.net.URL;
04
import java.util.List;
05

06
import com.cloud.pxxt.Config;
07
import com.jfinal.plugin.IPlugin;
08
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
09
import com.jfinal.plugin.activerecord.Model;
10
import com.jfinal.util.StringKit;
11

12
/**
13 www.2cto.com
* 自动扫包
14
*/
15
public class AutoScanPlugin implements IPlugin {
16
private ActiveRecordPlugin arp;
17

18
private TableNameStyle tableNameStyle;
19

20
public AutoScanPlugin(ActiveRecordPlugin arp) {
21
this.arp = arp;
22
}
23
public AutoScanPlugin(ActiveRecordPlugin arp,TableNameStyle tableNameStyle) {
24
this.arp = arp;
25
this.tableNameStyle = tableNameStyle;
26
}
27

28
@Override
29
public boolean start() {
30

try {
31
registModel(AutoScanPlugin.class.getResource("/").getFile(), "classes/");
32
} catch (Exception e) {
33
throw new RuntimeException(e);
34
}
35
return true;
36
}
37

38
@Override
39
public boolean stop() {
40
return true;
41
}
42

43
private void registModel(String fileDir, String pre) throws Exception {
44
List classList = FileSearcher.findFiles(fileDir, "*.class");
45
for (File classFile : classList) {
46
String className = getClassName(classFile, pre);
47
Class clazz = Class.forName(className);
48
if (clazz.getSuperclass() == Model.class) {
49
String tableName = clazz.getSimpleName();
50
if(tableNameStyle==TableNameStyle.UP){
51
tableName =tableName.toUpperCase();
52
}else if(tableNameStyle==TableNameStyle.LOWER){
53
tableName =tableName.toLowerCase();
54
}else{
55
tableName =StringKit.firstCharToLowerCase(tableName);
56

57
}
58
arp.addMapping(tableName, clazz);
59
}
60
}
61
}
62

63
private static String getClassName(File classFile, String pre) {
64
String objStr = classFile.toString().replaceAll("\\\\", "/");
65
String className;
66
className = objStr.substring(objStr.indexOf(pre)+pre.length(),objStr.indexOf(".class"));
67
if (className.startsWith("/")) {
68
className = className.substring(className.indexOf("/")+1);
69
}
70
return className.replaceAll("/", ".");
71
}
72

73
}
1
package com.jfin