面向切面编程,可以降低程序模块的耦合到最低,甚至可以不知道交互双方的存在
如,拦截sql,输出log,事务处理,数据统计等等,都可以用到
好处是降低耦合,不干涉模块的完整性
一般的步骤是:
1、用@Aspect标注一个类为切面类,用@Around、@Before等标注方法作为接入点做写拦截的处理,
特别注意的是拦截的方法的正则要测试清楚,调试多次就可以了
2、初始化这个类
如下例子:
@Aspect
public class SlowSqlMonitor {
@Around("execution(public * cn.pconline.babylib2.repository.AbstractRepository.*(..))")
public Object monitor(ProceedingJoinPoint pjp) throws Throwable {
Object arg = pjp.getArgs()[0];System.out.println("fsdfs");
String sql = null;
if(arg.getClass().getName().indexOf("PreparedStatementCreatorImpl")!=-1){
sql = arg.toString();
//第一个中括号是sql
sql = sql.substring(sql.indexOf("[")+1,sql.indexOf("]"));
}else{
sql = arg.toString();
}
long beginTime = System.currentTimeMillis();
try {
return pjp.proceed();
} finally {
long endTime = System.currentTimeMillis();
//if(beginTime + 1000 < endTime){
// System.out.println("time:"+(endTime-beginTime));
System.out.println(sql);
//}
}
}
}
然后可以测试效果了