springboot使用AOP实现切面编程

16 篇文章 0 订阅
10 篇文章 0 订阅

之前看日志里面有用到aop的技术所以想照着做一个过程如下

1创建一个@interface文件

package io.sirc.common.annotation;

import java.lang.annotation.*;

/**
 * 系统日志注解
 *
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysQueryLog {

	String value() default "";
}

2创建一个调用它的类,注意其中地址指向io.sirc.common.annotation.SysQueryLog是前面那货的地址

package io.sirc.common.aspect;

import io.sirc.common.utils.HttpContextUtils;
import io.sirc.common.utils.IPUtils;
import io.sirc.common.utils.R;
import io.sirc.modules.sea.entity.GetDataResponse;
import io.sirc.modules.sys.entity.SysQueryLogEntity;
import io.sirc.modules.sys.entity.SysUserEntity;
import io.sirc.modules.sys.service.SysQueryLogService;
import io.sirc.modules.sys.service.SysUserService;
import net.sf.json.JSONObject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


/**
 * 系统日志,切面处理类
 *
 */
@Aspect
@Component
public class SysQueryLogAspect {
	@Value("${isLocal}")
	private  boolean isLocal;

	@Autowired
	private SysQueryLogService sysQueryLogService;

    @Autowired
    private SysUserService sysUserService;
	
	@Pointcut("@annotation(io.sirc.common.annotation.SysQueryLog)")
	public void logPointCut() { 
		
	}
}

3.在SysQueryLogAspect 中添加方法,当然可以使用好几种标签@before,@after之类的  因为我现在需要的是进来之前判断参数中是否含有某些值 ,如果存在则中断不执行,执行方法后在执行日志插入操作,就使用@Around了,这样一下俩都能实现,

其中point是传进方法的参数,result是返回回去的值 ,point.proceed()是执行需要的接口,写在这上面的是调用接口之前执行的方法,写在下面的是执行之后的方法

@Around("logPointCut()")
	public GetDataResponse around(ProceedingJoinPoint point) throws Throwable {
        GetDataResponse result = new GetDataResponse();
        long beginTime = System.currentTimeMillis();
		//执行时长(毫秒)
		
		JSONObject jo = getParam(point);
        if(!isQueryLock(jo)) {
            result.setData(new R().ok().put("message","当前账号和ip已被锁定,请稍后再试。").toString());
            return result;
        }
        if(!isCompatible(jo)) {
            result.setData(new R().ok().put("message","当前账号和ip不匹配").toString());
            return result;
        }
        result= (GetDataResponse) point.proceed();
        long time = System.currentTimeMillis() - beginTime;
        saveSysQueryLog(jo, time);

		return result;
	}

4.在接口前面加上标签

@SysQueryLog
    public GetDataResponse getDataRequest(@RequestParam Map<String, Object> params) {
    //执行接口代码~~~~~~~~~~~~~~~~~
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值