Android Realm数据库配合aop框架封装

2017-06-19  本文已影响0人  nowind2018

Android Realm数据库配合aop框架封装

Realm数据库的使用,网上的介绍有很多,配置什么的这里就不写了,本文主要提供了一个新的封装思路,realm+AspectJ实现aop框架封装。

我们都知道,对于realm实现增、删、改、查的时候,一般的代码是这么写的。

<pre>
public booleaninsertOrUpdate(RealmObject object) {
try {
realm.beginTransaction();
realm.insertOrUpdate(object);
realm.commitTransaction();
return true;
} catch (Exception e) {
e.printStackTrace();
realm.cancelTransaction();
return false;
}
}
</pre>
其中对数据库的所有操作都需要执行
<pre>
realm.beginTransaction();
XXX//你的业务代码
realm.commitTransaction();
//若出错,执行realm.cancelTransaction();
</pre>
也就意味着在你的业务代码的执行前后都需要增加这样的固定格式的代码,如果此时每个方法里还需要查看耗时,则每个方法都需要增加相应的逻辑,显然,这样重复的工作不是我们想要的。那么这时Aop框架就可以解决这个问题了。
这里我们选用的是AspectJ库进行Aop框架的封装,下面简单介绍下配置:
1、gradle.build配置中加上AspectJ的配置库:
<pre>
compile 'org.aspectj:aspectjrt:1.8.10'
</pre>
2、buildScript中增加配置项:
<pre>
buildscript {
repositories{
mavenCentral()
}
dependencies{
classpath 'org.aspectj:aspectjtools:1.8.10'
classpath 'org.aspectj:aspectjweaver:1.8.10'
}
}
</pre>
3、增加log打印信息:
<pre>
import org.aspectj.bridge.IMessage
import org.aspectj.bridge.MessageHandler
import org.aspectj.tools.ajc.Main

final def log = project.logger
final def variants = project.android.applicationVariants

variants.all { variant ->
if (!variant.buildType.isDebuggable()) {
log.debug("Skipping build type '&(variant.buildType.name)'.");
return;
}
org.gradle.api.tasks.compile.JavaCompile javaCompile = variant.javaCompile
javaCompile.doLast {
String[] args = ["-showWeaveInfo","-1.8",
"-inpath",javaCompile.destinationDir.toString(),
"-aspectpath",javaCompile.classpath.asPath,
"-d",javaCompile.destinationDir.toString(),
"-classpath",javaCompile.classpath.asPath,
"-bootclasspath",project.android.bootClasspath.join(File.pathSeparator)
]
log.debug("ajc args: " + Arrays.asList(args));
MessageHandler handler = new MessageHandler(true);
new Main().run(args,handler);
for(IMessage message : handler.getMessages(null,true)){
switch (message.getKind()){
case IMessage.ABORT:
case IMessage.ERROR:
case IMessage.FAIL:
log.error message.message,message.thrown
break;
case IMessage.WARNING:
log.warn message.message,message.thrown
break;
case IMessage.INFO:
log.info message.message,message.thrown
break;
case IMessage.DEBUG:
log.debug message.message,message.thrown
break;
}
}
}
}
</pre>
完成以上配置就可以进行aop框架的封装了。封装步骤如下:
1、利用注解方式定义需要进行aop的方法:
<pre>
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AopAnnotationInterface {
String value();
}
</pre>
2、Aop嵌码,此处有详细注释,核心功能在这里:
<pre>
@Aspect//aspectJ api
public class AopAspectUtils {
//切面由哪些方法组成
//方法中带有BehaviorTrace注解的任意类的任意方法就属于这个切面
@Pointcut("execution(@com.duke.realm_test.annotation.AopAnnotationInterface * *(..))")
public void methodAnnotatedWithBehavior(){}

//针对切面进行编程
@Around("methodAnnotatedWithBehavior()")
public Object weaveJointPoint(ProceedingJoinPoint joinPoint){
    long begin = System.currentTimeMillis();
    Realm realm = Realm.getDefaultInstance();
    realm.beginTransaction();//执行方法前做的操作
    Object obj= null;
    try {
        obj = joinPoint.proceed();//执行方法
    } catch (Throwable throwable) {
        realm.cancelTransaction();
        throwable.printStackTrace();
        return obj;
    }
    realm.commitTransaction();//执行方法后的操作
    long duration = System.currentTimeMillis() - begin;

    //获取功能名称,利用的反射api
    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    AopAnnotationInterface aopAnnotationInterface = methodSignature.getMethod().getAnnotation(AopAnnotationInterface.class);
    String funcName = aopAnnotationInterface.value();
    Log.i("yunli",funcName + " 被执行,耗时: " + duration );
    return obj;
}

}

</pre>
3、方法的使用:
<pre>
@AopAnnotationInterface("addRealmList")
public boolean addRealmList(List<? extends RealmObject> list){
boolean res = false;
try {
mRealm.copyToRealmOrUpdate(list);
res = true;
}catch (Exception e){
}
return res;
}
</pre>
这里你只需要添加@AopAnnotationInterface注解,接下来去实现你的业务代码就可以了。
下载demo链接:
github:
https://github.com/ahjxly/realmAspectJ.git
csdn:
http://download.csdn.net/detail/ahjxly/9874659

上一篇下一篇

猜你喜欢

热点阅读