@Around("bean(sysRoleServiceImpl)")
我们要为这个角色模块的任意方法添加日志处理功能
ProceedingJoinPoint 连接点封装特定的方法信息
环绕通知内部的bean表达式为一个切入点表达-扩展功能在哪个点进行切入,什么时候加扩展功能,在什么位置加功能?
jointPoint.proceed();是一个连接点
bean(sysRoleServiceImpl)切入点,在bean的sysRoleServiceImpl业务类里面的所有方法执行时加日志
这个通知看成为封装了扩展业务的方法对象
package com.jt.common.aspect;
import java.util.Arrays;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jt.common.util.IPUtils;
import com.jt.dao.SysLogDao;
import com.jt.entity.SysLog;
import com.jt.entity.SysUser;
/**
* 日志横切面对象
* @Aspect 用于描述此类为一个切面对象
*
*/
@Aspect
@Service
public class SysLogAspect {
@Autowired
private SysLogDao sysLogDao;
/**
* @Around 描述的方法为一个环绕通知
* 环绕通知:目标方法执行之前和之后都可以执行
* 环绕通知内部的bean表达式为一个切入点表达-扩展功能在哪个点进行切入,什么时候加扩展功能,在什么位置加功能?
*
* @param ProceedingJoinPoint-连接点对象:封装了(特定)具体业务的方法信息
* @return
* @throws Throwable
*/
@Around("bean(sysRoleServiceImpl)")
public Object aroundMethod(ProceedingJoinPoint jointPoint) throws Throwable{
long startTime=System.currentTimeMillis();
//调用执行目标方法(result为目标方法执行结果)
Object result=jointPoint.proceed();
long endTime=System.currentTimeMillis();
//保存日志信息并存储到数据库
saveObject(jointPoint, endTime-startTime);
return result;
}
private void saveObject(ProceedingJoinPoint jointPoint,long time){
Class> targetCls = jointPoint.getTarget().getClass();
//方法签名-方法名和参数列表
Signature s = jointPoint.getSignature();
System.out.println(targetCls.getName()+"."+s.getName()+"->totalTime="+(time));
String methodName = targetCls.getName()+"."+s.getName();
Object[] args = jointPoint.getArgs();
//封装日志信息
SysLog log=new SysLog();
log.setIp(IPUtils.getIpAddr());
log.setMethod(methodName);
log.setParams(Arrays.toString(args));
SysUser user = (SysUser)SecurityUtils.getSubject().getPrincipal();
System.out.println("SysLogAspectUser"+user);
log.setUsername(user.getUsername());
log.setTime(time);
//保存日志信息
sysLogDao.insertObject(log);
}
}//基于OCP-open-close-principle原则进行功能扩展:例如日志处理