Spring AOP面向切面编程之日志记录

版权声明:原创作品转载必须标明出处,谢谢配合! https://blog.csdn.net/qq_38704184/article/details/85113734

实际项目中我们往往需要将一些重要的操作,以日志的形式进行保存,当机器宕机的时候,可以通过查找日志,定位出错位置,方便恢复。

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里面配置日志保存地址为我们的本地,实际开发中,日志保存在集群中,并且是以天为单位进行动态滚动进行保存的。

猜你喜欢

转载自blog.csdn.net/qq_38704184/article/details/85113734
今日推荐