1.使用@Aspect注解标注一个java类,Spring将自动识别该类做为切面Bean。java
@Aspect public class ExceptionAndLogAspect { }
2.在Spring配置文件中添加這個切面Bean,并启动@AspectJ支持。apache
<!-- 配置切面的类 --> <bean id="ExceptionAndLogAspect" class="com.student.xl.util.ExceptionAndLogAspect"></bean> <!--启动@AspectJ支持--> <aop:aspectj-autoproxy/>
3.添加加强处理测试
import org.apache.log4j.Logger; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; /** * 统一处理异常和日志的切面类 * @author louzi */ @Aspect public class ExceptionAndLogAspect { Logger log = Logger.getLogger(this.getClass().getName()); //Before加强:在目标方法被执行的时候织入加强 //匹配com.student.xl包下面的全部类的全部方法的执行做为切入点 @Before("execution(* com.student.xl.*.*.*(..))") public void beforeWave(JoinPoint joinPoint){ String className = joinPoint.getTarget().getClass().getName(); String methodName = joinPoint.getSignature().getName(); System.out.println("进入"+className+"类的"+methodName+"方法。"); } //AfterReturning加强:在目标方法正常完成后被织入 //rvt是目标方法的返回值 @AfterReturning(returning="rvt",pointcut="execution(* com.student.xl.*.*.*(..))") public void afterWave(Object rvt){ System.out.println("得到目标方法返回值:"+rvt); } //AfterThrowing加强:处理程序中未处理的异常 //ex是目标方法拋出的异常 @AfterThrowing(throwing="ex",pointcut="execution(* com.student.xl.*.*.*(..))") public void exceptionDispose(JoinPoint joinPoint,Throwable ex){ String className = joinPoint.getTarget().getClass().getName(); //切入方法所属类名 String methodName = joinPoint.getSignature().getName(); //切入的方法名 Object[] params = joinPoint.getArgs(); //目标方法传入的参数 String param = "入参为:"; if(params != null && params.length > 0){ for(Object p : params){ param += p + ","; } param = param.substring(0,param.lastIndexOf(",")); } log.error("[Exception]:["+className+"]"+methodName+":" + ex); System.out.println("【"+className+"】:"+methodName+"执行时出现异常:"+ex+"。"); System.out.println(param); } }
4.如今能够写个类作测试了。this