Spring AOP 拦截器简单应用

package com.aoptest;

import java.lang.reflect.Method;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;

public class MethodAdvice implements MethodInterceptor, MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice
{
	private static final Log log = LogFactory.getLog(MethodAdvice.class);

	@Override
	public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable
	{
		log.info("AfterReturningAdvice begin");
		log.info("Class:" + target.getClass().getName());
		log.info("Method:" + method.getName());
		log.info("args:" + args);
		log.info("returnValue:" + returnValue);
		log.info("AfterReturningAdvice end");
	}

	@Override
	public void before(Method method, Object[] args, Object target) throws Throwable
	{
		log.info("MethodBeforeAdvice begin");
		log.info("Class:" + target.getClass().getName());
		log.info("Method:" + method.getName());
		log.info("args:" + args);
		log.info("MethodBeforeAdvice end");
	}

	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable
	{
		log.info("MethodInterceptor begin");
		log.info("Class:" + invocation.getClass().getName());
		log.info("Method:" + invocation.getMethod());
		log.info("args:" + invocation.getArguments());
		log.info("MethodInterceptor end");
		return invocation.proceed();
	}
	
	public void afterThrowing(Method method, Object[] args, Object target, Exception ex)
	{
		log.info("ThrowsAdvice begin");
		log.info("Class:" + target.getClass().getName());
		log.info("Method:" + method.getName());
		log.info("args:" + args);
		log.info("Exception:" + ex);
		log.info("ThrowsAdvice end");
	}
}

 

<bean id="methodAdvice" class="com.aoptest.MethodAdvice" />
<aop:config>
         <!--切入点 -->
	<aop:pointcut id="methodPoint"	expression="execution(public * com.test.*(..))"/>
        <!--在该切入点使用自定义拦截器 -->
	<aop:advisor pointcut-ref="methodPoint" advice-ref="methodAdvice"/>
</aop:config>
 

 

 

你可能感兴趣的:(spring,AOP,拦截器)