天天看點

Spring AOP面向切面程式設計之日志記錄

實際項目中我們往往需要将一些重要的操作,以日志的形式進行儲存,當機器當機的時候,可以通過查找日志,定位出錯位置,友善恢複。

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>
           

4:最好是在log4j.properties裡面配置日志儲存位址為我們的本地,實際開發中,日志儲存在叢集中,并且是以天為機關進行動态滾動進行儲存的。