java环绕通知的应用_AOP-环绕通知-在目标方法执行之前和执行之后执行

@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原则进行功能扩展:例如日志处理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值