采用Spring AOP实现日志记录

切面类:

package io.steveguoshao.spring.common.aspect;

import org.aspectj.lang.JoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class LogAspect {
	
	protected Logger log = LoggerFactory.getLogger(getClass());
	
	/**
	 * 在方法前调用
	 * beforeAlgorithmCall
	 * @param jp 
	 * void
	 * @exception 
	 * @since  1.0.0
	 */
	public void beforeCall(JoinPoint jp) {
		String className = jp.getTarget().getClass().getName();
		className = className.substring(className.lastIndexOf(".") - 1);
		log.info("类{}开始调用方法{}", className, jp.getSignature().getName());
	}
	
	/**
	 * 在方法后调用
	 * afterAlgorithmCall
	 * @param jp 
	 * void
	 * @exception 
	 * @since  1.0.0
	 */
	public void afterCall(JoinPoint jp) {
		String className = jp.getTarget().getClass().getName();
		className = className.substring(className.lastIndexOf(".") - 1);
		log.info("类{}调用方法{}结束", className, jp.getSignature().getName());
	}
	
	/**
	 * 在方法返回之后调用
	 * afterReturningAlgorithmCall
	 * @param jp
	 * @param retVal 
	 * void
	 * @exception 
	 * @since  1.0.0
	 */
	public void afterReturningCall(JoinPoint jp, Object retVal) {
		String className = jp.getTarget().getClass().getName();
		className = className.substring(className.lastIndexOf(".") - 1);
		log.info("类{}调用方法{}的结果:", className, jp.getSignature().getName());
		YourObject yourObject = (YourObject)retVal;
		// todo
	}
	
}

Spring xml配置:

<aop:config expose-proxy="true" proxy-target-class="true">
   	<aop:aspect id="logAspect" ref="logAspect">
		<aop:pointcut expression="execution(* io.steveguoshao.spring.web.controller.*.add(..)) 
			or execution(* io.steveguoshao.spring.web.controller.*.update(..))" id="logPointcut"/>
		<aop:before method="beforeCall" pointcut-ref="logPointcut"/>
		<aop:after method="afterCall" pointcut-ref="logPointcut"/>
		<aop:after-returning method="afterReturningCall" pointcut-ref="logPointcut" 
			arg-names="retVal" returning="retVal"/>
    </aop:aspect>
</aop:config>



你可能感兴趣的:(spring,AOP,日志,log)