spring轻松实现aop

1 篇文章 0 订阅

教程以实现日志记录为基础

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

首先你得有依赖

然后来一个注解类

//可使用此注解的 obj(对象,这里是方法)
@Target(ElementType.METHOD)
//用来说明该注解类的生命周期-运行时
@Retention(RetentionPolicy.RUNTIME)
//标记为注解
@Documented
public @interface SysLog {

	String value() default "";
}

最后动态代理一下

@Aspect
@Component
public class SysLogAspect {
	@Autowired
	private SysLogService sysLogService;
        //就是上面那个注解类的位置
	@Pointcut("@annotation(com.**.**.annotation.SysLog)")
	public void logPointCut() { 

	}

	@Around("logPointCut()")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		long beginTime = System.currentTimeMillis();
		//执行方法
		Object result = point.proceed();
		//执行时长(毫秒)
		long executeTime = System.currentTimeMillis() - beginTime;

		//保存日志
		saveSysLog(point, executeTime);

		return result;
	}

	private void saveSysLog(ProceedingJoinPoint joinPoint, long executeTime) {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();

		SysLogEntity mySysLog = new SysLogEntity();
		SysLog syslog = method.getAnnotation(SysLog.class);
		if(syslog != null){
			//注解上的描述
			mySysLog.setOperation(syslog.value());
		}
        //className
		String className = joinPoint.getTarget().getClass().getName();
        //请求的方法名
		String methodName = signature.getName();
		mySysLog.setMethod(className + "." + methodName + "()");

		//请求的参数
		Object[] args = joinPoint.getArgs();
		try{
			String params = new Gson().toJson(args[0]);
			mySysLog.setParams(params);
		}catch (Exception e){

		}

		//获取request
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
		//设置IP地址
		mySysLog.setIp(IPUtils.getIpAddr(request));

		mySysLog.setTime(executeTime);
		mySysLog.setCreateDate(new Date());
		//保存系统日志
		sysLogService.save(mySysLog);
	}

大功告成, 在需要日志记录的方法(一般为service层)上面注解个 @SysLog 就可以了,很简单, 如果发现没报错, 死活就是不能成功, 那你的service一般都是被springmvc扫描到了,springMVC会先扫描加载,当springMVC扫描后,扫描过的部分,spring就不会去扫描了,于是spring中的AOP就不能发挥作用了

当然我用的是springboot 没有出现这个问题

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值