實際項目中我們往往需要将一些重要的操作,以日志的形式進行儲存,當機器當機的時候,可以通過查找日志,定位出錯位置,友善恢複。
1:首先導入spring支援的AOP架包
2:編寫将要進行切面工作的類
/**
*
*/
package com.zhiyou100.aspect;
import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
/**
* @author Administrator
*
*/
@Aspect
@Component
public class LoggingAspect {
//前置通知
public void beforeMethod(JoinPoint joinPoint) {
String methodName =
joinPoint.getSignature().getName();
Object[] args =
joinPoint.getArgs();
long timeMillis =
System.currentTimeMillis();
System.out.println("start execute time:"
+ timeMillis + ","
+ methodName
+ " start execute,args:"
+ Arrays.toString(args));
}
//最終通知
public void afterMethod(JoinPoint joinPoint) {
String methodName =
joinPoint.getSignature().getName();
long times = System.currentTimeMillis();
System.out.println("after execute time:"
+ times
+ ","
+ methodName
+ " execute end");
}
//後置通知
public void afterReturning(JoinPoint joinPoint, Object result) {
String methodName =
joinPoint.getSignature().getName();
System.out.println(methodName
+ " execute result:"
+ result);
}
//異常通知
public void afterThrowing(JoinPoint joinPoint, Exception e) {
String methodName =
joinPoint.getSignature().getName();
System.out.println(methodName
+ " execute exception:"
+ e);
}
}
3:納入spring容器
<aop:aspectj-autoproxy proxy-target-class="true"/>
<bean id="aspect" class=""/>
<!--AOP事務 -->
<aop:config proxy-target-class="true">
<aop:aspect ref="aspect">
<aop:pointcut
expression="execution(*com.zhiyou100.controller.*.*(..))"
id="pointCut"/>
<aop:before
method="beforeMethod"
pointcut-ref="pointCut"/>
<aop:after-returning
method="afterReturning"
pointcut-ref="pointCut"
returning="result"/>
<aop:after
method="afterMethod"
pointcut-ref="pointCut"/>
<aop:after-throwing
method="afterThrowing"
pointcut-ref="pointCut"
throwing="e"/>
</aop:aspect>
</aop:config>