java学习

java学习

 

spring中aop的annotation的写法

四种通知的执行地方:前置通知
try{
业务代码
后置通知
} catch{
异常通知
} finally{
最终通知
}
1.需要的jar包:aspectjrt.jar,aspectjweaver.jar,cglib-nodep-2.1.3.jar
2.在配置文件中加入

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:p="http://www.springframework.org/schema/p"
         xmlns:aop="http://www.springframework.org/schema/aop"
         xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd

">
<!-- 让spring支持annotation的aop -->
<aop:aspectj-autoproxy/>
<!-- 把切面类交给spring -->
<bean id="myAspece" class="com.yjw.aspect.MyAspect"/>

</beans>

package com.yjw.aspect;


import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
//定义切面类,存放通知
@Aspect
public class MyAspect {

 //切入点
 /**第一个星号代表返回任何类型的数据,bean后的两个点代表本包及其子包,
  * 第二个星号代表中间的所有的类;
  * 第三个星号代表中间的所有的方法;
  * (..)小括号代表参数列表,两个点代表参数类型不限
  */
 
 @Pointcut("execution(* com.yjw.dao..*.*(..))")
 public void  pointCut(){}
 //前置通知
 @Before(" pointCut()")
 public void  beforeAdvice(){
  System.out.println("前置通知");
 }
 //异常通知,接收异常信息
 @AfterThrowing( pointcut=" pointCut()",throwing="ex")
 public  void  exceptionAdvice(Exception  ex){
  System.out.println("异常出现"+ex.getMessage());
 }
 //后置通知,可以接收方法的返回值
 @AfterReturning( pointcut=" pointCut()",returning="value")
 public  void  afterReturningAdvice(Object  value){
  System.out.println("后置通知"+value);
 }
 //最终通知
 @After(" pointCut()")
 public  void  afterAdvice(){
  System.out.println("zuizhong");
 }

}


posted on 2013-04-29 11:35 杨军威 阅读(229) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜