SpringAOP案例

本文介绍了如何使用Spring AOP进行异常信息收集、业务方法执行时间统计以及事务控制。详细讲解了开发事务和权限控制注解、切面的实现以及ThreadLocal在权限控制中的应用,通过ThreadLocal确保每个用户在线程中拥有独立的权限列表,以实现安全的权限管理。
摘要由CSDN通过智能技术生成

1. 异常信息收集
在业务方法执行时,如果有异常抛出,则根据异常信息记录日志

package cn.tedu.em.aspect;

import java.io.FileWriter;
import java.util.Date;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class LoggerAspect {
   
	@AfterThrowing(value = "execution(* cn.tedu.em.service..*.*(..))",throwing="e")
	public void afterThrowing(JoinPoint jp,Throwable e) throws Exception{
   
		Class clz = jp.getTarget().getClass();
		String name = jp.getSignature().getName();
		String eMsg = e.getMessage();
		FileWriter writer = new FileWriter("err.log",true);
		String info = new Date().toLocaleString()+"--"+clz+"--"+name+"--"+eMsg;
		writer.write(info+"\r\n");
		writer.flush();
		writer.close();
	}
}

2.统计业务方法执行的时间
统计所有业务方法执行时的耗时

package cn.tedu.em.aspect;

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.stereotype.Component;

@Component
@Aspect
public class UseTimeAspect {
   
	@Pointcut("execution(* cn.tedu.em.service..*(..))")
	public void mx(){
   }
	
	@Around("mx()")
	public Object around(ProceedingJoinPoint pjp) throws Throwable{
   
		long begin = System.currentTimeMillis();
		Object obj = pjp.proceed();
		long end = System.currentTimeMillis();
		System.out.println("--useTime:["+(end - begin)+"]--");
		return obj;
	}
}

3. 实现事务控制
通过AOP实现事务控制,通过注解来标识方法是否需要事务

a. 开发事务注解

package cn.tedu.em.anno;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Trans {
   

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值