spring aop学习--拦截controller

关于aop的一些理论,不懂的同学可以参考下以下的链接:
aop理论:
http://blog.csdn.net/csh624366188/article/details/7651702
http://www.cnblogs.com/davidwang456/p/4013631.html

Aspectj切入点语法:
http://blog.csdn.net/lk7688535/article/details/51989746

拦截controller:
http://blog.csdn.net/shi_longyan/article/details/70917447
http://www.cnblogs.com/Frank-Hao/p/5787813.html

进入正题:
目标是为登录行为添加日志。

选择的是注解的实现方式。(aop有4种实现方式,自行百度;完整的注解应该是用describetion的,后面再讲)
那么现在就两个步骤:
1.写好切面;
2.修改xml文件。

1.切面代码
package swt.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 应用日志
 *
 */
@Component
@Aspect
public class AppLogAspect {

	@Pointcut("execution(* swt.controller.sys..*.*(..))")//此处切入点语法参见连接
	public void allMethod(){}
	
	@Before("allMethod()")
	public void before(JoinPoint call){
		String className = call.getTarget().getClass().getName();
		String methidName = call.getSignature().getName();
		System.out.println("前置通知:"+className+"类的"+methidName+"方法开始了");
	}
	
	@AfterReturning("allMethod()")
	public void afterReturn(){
		System.out.println("后置通知:方法正常结束了");
	}
	
	@AfterThrowing("allMethod()")
	public void afterThrow(){
		System.out.println("异常后通知:方法执行异常");
	}
	
	@After("allMethod()")
	public void after(){
		System.out.println("最终通知:无论方法是否正常执行完成,都会在这里结束");
	}
	
}

2.将原spring-bean.xml中的aop的基础上,再在spring-mvc.xml中加上引用。(如果注释掉原bean中的引用,将无法拦截controller)
原spring-bean.xml:
<aop:aspectj-autoproxy/>
在spring-mvc.xml中加上:
<aop:aspectj-autoproxy proxy-target-class="true" />

测试ok。

补充一些其他的注意事项:
1.多个切点适用同一个方法,用||连接:
execution(* com.travelsky.ccboy.dao..*.find*(..)) ||  execution(* com.travelsky.ccboy.dao..*.query*(..))"


2.抛出异常和返回,注意加上throwing = "ex"和returning = "result":

@AfterThrowing(value = "declareJoinPointExpression()", throwing = "ex")

@AfterReturning(value = "declareJoinPointExpression()", returning = "result")



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值