1. 程式人生 > >Spring AOP面向切面程式設計之日誌記錄

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裡面配置日誌儲存地址為我們的本地,實際開發中,日誌儲存在叢集中,並且是以天為單位進行動態滾動進行儲存的。