`
s103y
  • 浏览: 112617 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

AOP(转)

阅读更多

Aspect Oriented Programming的缩写,意为:面向方法编程 

此前对于AOP的使用仅限于声明式事务,除此之外在实际开发中也没有遇到过与之相关的问题。最近项目中遇到了以下几点需求,仔细思考之后,觉得采用AOP 来解决。一方面是为了以更加灵活的方式来解决问题,另一方面是借此机会深入学习Spring AOP相关的内容。本文是权当本人的自己AOP学习笔记,以下需求不用AOP肯定也能解决,至于是否牵强附会,仁者见仁智者见智。

  1. 对部分函数的调用进行日志记录,用于观察特定问题在运行过程中的函数调用情况
  2. 监控部分重要函数,若抛出指定的异常,需要以短信或邮件方式通知相关人员
  3. 金控部分重要函数的执行时间

    事实上,以上需求没有AOP也能搞定,只是在实现过程中比较郁闷摆了。

  1. 需要打印日志的函数分散在各个包中,只能找到所有的函数体,手动添加日志。然而这些日志都是临时的,待问题解决之后应该需要清除打印日志的代码,只能再次手动清除^_^!
  2. 类似1的情况,需要捕获异常的地方太多,如果手动添加时想到很可能明天又要手动清除,只能再汗。OK,该需求相对比较固定,属于长期监控的范畴,并不需求临时添加后再清除。然而,客户某天要求,把其中20%的异常改为短信提醒,剩下的80%改用邮件提醒。改之,两天后,客户抱怨短信太多,全部改成邮件提醒...
  3. 该需求通常用于监控某些函数的执行时间,用以判断系统执行慢的瓶颈所在。瓶颈被解决之后,烦恼同情况1


    终于下定决心,采用AOP来解决!代码如下:

 

    切面类TestAspect

Java代码 复制代码 收藏代码
  1. package com.spring.aop;   
  2. /**  
  3.  * 切面  
  4.  *  
  5.  */  
  6. public class TestAspect {   
  7.   
  8.     public void doAfter(JoinPoint jp) {   
  9.         System.out.println("log Ending method: "  
  10.                 + jp.getTarget().getClass().getName() + "."  
  11.                 + jp.getSignature().getName());   
  12.     }   
  13.   
  14.     public Object doAround(ProceedingJoinPoint pjp) throws Throwable {   
  15.         long time = System.currentTimeMillis();   
  16.         Object retVal = pjp.proceed();   
  17.         time = System.currentTimeMillis() - time;   
  18.         System.out.println("process time: " + time + " ms");   
  19.         return retVal;   
  20.     }   
  21.   
  22.     public void doBefore(JoinPoint jp) {   
  23.         System.out.println("log Begining method: "  
  24.                 + jp.getTarget().getClass().getName() + "."  
  25.                 + jp.getSignature().getName());   
  26.     }   
  27.   
  28.     public void doThrowing(JoinPoint jp, Throwable ex) {   
  29.         System.out.println("method " + jp.getTarget().getClass().getName()   
  30.                 + "." + jp.getSignature().getName() + " throw exception");   
  31.         System.out.println(ex.getMessage());   
  32.     }   
  33.   
  34.     private void sendEx(String ex) {   
  35.         //TODO 发送短信或邮件提醒   
  36.     }   
  37. }   
package com.spring.aop;
/**
 * 切面
 *
 */
public class TestAspect {

    public void doAfter(JoinPoint jp) {
        System.out.println("log Ending method: "
                + jp.getTarget().getClass().getName() + "."
                + jp.getSignature().getName());
    }

    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        long time = System.currentTimeMillis();
        Object retVal = pjp.proceed();
        time = System.currentTimeMillis() - time;
        System.out.println("process time: " + time + " ms");
        return retVal;
    }

    public void doBefore(JoinPoint jp) {
        System.out.println("log Begining method: "
                + jp.getTarget().getClass().getName() + "."
                + jp.getSignature().getName());
    }

    public void doThrowing(JoinPoint jp, Throwable ex) {
        System.out.println("method " + jp.getTarget().getClass().getName()
                + "." + jp.getSignature().getName() + " throw exception");
        System.out.println(ex.getMessage());
    }

    private void sendEx(String ex) {
        //TODO 发送短信或邮件提醒
    }
} 

 

 

Java代码 复制代码 收藏代码
  1. package com.spring.service;   
  2. /**  
  3.  * 接口A  
  4.  */  
  5. public interface AService {   
  6.        
  7.     public void fooA(String _msg);   
  8.   
  9.     public void barA();   
  10. }  
package com.spring.service;
/**
 * 接口A
 */
public interface AService {
    
    public void fooA(String _msg);

    public void barA();
}

 

Java代码 复制代码 收藏代码
  1. package com.spring.service;   
  2. /**  
  3.  *接口A的实现类  
  4.  */  
  5. public class AServiceImpl implements AService {   
  6.   
  7.     public void barA() {   
  8.         System.out.println("AServiceImpl.barA()");   
  9.     }   
  10.   
  11.     public void fooA(String _msg) {   
  12.         System.out.println("AServiceImpl.fooA(msg:"+_msg+")");   
  13.     }   
  14. }  
package com.spring.service;
/**
 *接口A的实现类
 */
public class AServiceImpl implements AService {

    public void barA() {
        System.out.println("AServiceImpl.barA()");
    }

    public void fooA(String _msg) {
        System.out.println("AServiceImpl.fooA(msg:"+_msg+")");
    }
}

 

 

Java代码 复制代码 收藏代码
  1. package com.spring.service;   
  2.   
  3. /**  
  4.  *   Service类B  
  5.  */  
  6. public class BServiceImpl {   
  7.   
  8.     public void barB(String _msg, int _type) {   
  9.         System.out.println("BServiceImpl.barB(msg:"+_msg+" type:"+_type+")");   
  10.         if(_type == 1)   
  11.             throw new IllegalArgumentException("测试异常");   
  12.     }   
  13.   
  14.     public void fooB() {   
  15.         System.out.println("BServiceImpl.fooB()");   
  16.     }   
  17.   
  18. }  
package com.spring.service;

/**
 *   Service类B
 */
public class BServiceImpl {

    public void barB(String _msg, int _type) {
        System.out.println("BServiceImpl.barB(msg:"+_msg+" type:"+_type+")");
        if(_type == 1)
            throw new IllegalArgumentException("测试异常");
    }

    public void fooB() {
        System.out.println("BServiceImpl.fooB()");
    }

}

 

    ApplicationContext

Java代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>   
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xsi:schemaLocation="   
  6.             http://www.springframework.org/schema/beans   
  7.             http://www.springframework.org/schema/beans/spring-beans-2.0.xsd   
  8.             http://www.springframework.org/schema/aop   
  9.             http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"   
  10.     default-autowire="autodetect">   
  11.     <aop:config>   
  12.         <aop:aspect id="TestAspect" ref="aspectBean">   
  13.             <!--配置com.spring.service包下所有类或接口的所有方法-->   
  14.             <aop:pointcut id="businessService"  
  15.                 expression="execution(* com.spring.service.*.*(..))" />   
  16.             <aop:before pointcut-ref="businessService" method="doBefore"/>   
  17.             <aop:after pointcut-ref="businessService" method="doAfter"/>   
  18.             <aop:around pointcut-ref="businessService" method="doAround"/>   
  19.             <aop:after-throwing pointcut-ref="businessService" method="doThrowing" throwing="ex"/>   
  20.         </aop:aspect>   
  21.     </aop:config>   
  22.        
  23.     <bean id="aspectBean" class="com.spring.aop.TestAspect" />   
  24.     <bean id="aService" class="com.spring.service.AServiceImpl"></bean>   
  25.     <bean id="bService" class="com.spring.service.BServiceImpl"></bean>   
  26.   
  27. </beans>  
<?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:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
    default-autowire="autodetect">
    <aop:config>
        <aop:aspect id="TestAspect" ref="aspectBean">
            <!--配置com.spring.service包下所有类或接口的所有方法-->
            <aop:pointcut id="businessService"
                expression="execution(* com.spring.service.*.*(..))" />
            <aop:before pointcut-ref="businessService" method="doBefore"/>
            <aop:after pointcut-ref="businessService" method="doAfter"/>
            <aop:around pointcut-ref="businessService" method="doAround"/>
            <aop:after-throwing pointcut-ref="businessService" method="doThrowing" throwing="ex"/>
        </aop:aspect>
    </aop:config>
    
    <bean id="aspectBean" class="com.spring.aop.TestAspect" />
    <bean id="aService" class="com.spring.service.AServiceImpl"></bean>
    <bean id="bService" class="com.spring.service.BServiceImpl"></bean>

</beans>

 

    测试类AOPTest

Java代码 复制代码 收藏代码
  1. public class AOPTest extends AbstractDependencyInjectionSpringContextTests {   
  2.        
  3.     private AService aService;   
  4.        
  5.     private BServiceImpl bService;   
  6.        
  7.     protected String[] getConfigLocations() {   
  8.         String[] configs = new String[] { "/applicationContext.xml"};   
  9.         return configs;   
  10.     }   
  11.        
  12.        
  13.     /**  
  14.      * 测试正常调用  
  15.      */  
  16.     public void testCall()   
  17.     {   
  18.         System.out.println("SpringTest JUnit test");   
  19.         aService.fooA("JUnit test fooA");   
  20.         aService.barA();   
  21.         bService.fooB();   
  22.         bService.barB("JUnit test barB",0);   
  23.     }   
  24.        
  25.     /**  
  26.      * 测试After-Throwing  
  27.      */  
  28.     public void testThrow()   
  29.     {   
  30.         try {   
  31.             bService.barB("JUnit call barB",1);   
  32.         } catch (IllegalArgumentException e) {   
  33.                
  34.         }   
  35.     }   
  36.        
  37.     public void setAService(AService service) {   
  38.         aService = service;   
  39.     }   
  40.        
  41.     public void setBService(BServiceImpl service) {   
  42.         bService = service;   
  43.     }   
  44. }  
public class AOPTest extends AbstractDependencyInjectionSpringContextTests {
	
	private AService aService;
	
	private BServiceImpl bService;
	
	protected String[] getConfigLocations() {
		String[] configs = new String[] { "/applicationContext.xml"};
		return configs;
	}
	
	
	/**
	 * 测试正常调用
	 */
	public void testCall()
	{
		System.out.println("SpringTest JUnit test");
		aService.fooA("JUnit test fooA");
		aService.barA();
		bService.fooB();
		bService.barB("JUnit test barB",0);
	}
	
	/**
	 * 测试After-Throwing
	 */
	public void testThrow()
	{
		try {
			bService.barB("JUnit call barB",1);
		} catch (IllegalArgumentException e) {
			
		}
	}
	
	public void setAService(AService service) {
		aService = service;
	}
	
	public void setBService(BServiceImpl service) {
		bService = service;
	}
}

 

    运行结果如下:

Java代码 复制代码 收藏代码
  1. log Begining method: com.spring.service.AServiceImpl.fooA   
  2. AServiceImpl.fooA(msg:JUnit test fooA)   
  3. log Ending method: com.spring.service.AServiceImpl.fooA   
  4. process time: 0 ms   
  5. log Begining method: com.spring.service.AServiceImpl.barA   
  6. AServiceImpl.barA()   
  7. log Ending method: com.spring.service.AServiceImpl.barA   
  8. process time: 0 ms   
  9. log Begining method: com.spring.service.BServiceImpl.fooB   
  10. BServiceImpl.fooB()   
  11. log Ending method: com.spring.service.BServiceImpl.fooB   
  12. process time: 0 ms   
  13. log Begining method: com.spring.service.BServiceImpl.barB   
  14. BServiceImpl.barB(msg:JUnit test barB type:0)   
  15. log Ending method: com.spring.service.BServiceImpl.barB   
  16. process time: 0 ms   
  17.   
  18. log Begining method: com.spring.service.BServiceImpl.barB   
  19. BServiceImpl.barB(msg:JUnit call barB type:1)   
  20. log Ending method: com.spring.service.BServiceImpl.barB   
  21. method com.spring.service.BServiceImpl.barB throw exception   
  22. 测试异常  
log Begining method: com.spring.service.AServiceImpl.fooA
AServiceImpl.fooA(msg:JUnit test fooA)
log Ending method: com.spring.service.AServiceImpl.fooA
process time: 0 ms
log Begining method: com.spring.service.AServiceImpl.barA
AServiceImpl.barA()
log Ending method: com.spring.service.AServiceImpl.barA
process time: 0 ms
log Begining method: com.spring.service.BServiceImpl.fooB
BServiceImpl.fooB()
log Ending method: com.spring.service.BServiceImpl.fooB
process time: 0 ms
log Begining method: com.spring.service.BServiceImpl.barB
BServiceImpl.barB(msg:JUnit test barB type:0)
log Ending method: com.spring.service.BServiceImpl.barB
process time: 0 ms

log Begining method: com.spring.service.BServiceImpl.barB
BServiceImpl.barB(msg:JUnit call barB type:1)
log Ending method: com.spring.service.BServiceImpl.barB
method com.spring.service.BServiceImpl.barB throw exception
测试异常

 

    《Spring参考手册》中定义了以下几个AOP的重要概念,结合以上代码分析如下:

  • 切面(Aspect) :官方的抽象定义为“一个关注点的模块化,这个关注点可能会横切多个对象”,在本例中,“切面”就是类TestAspect所关注的具体行为,例如,AServiceImpl.barA()的调用就是切面TestAspect所关注的行为之一。“切面”在ApplicationContext中<aop:aspect>来配置。
  • 连接点(Joinpoint) :程序执行过程中的某一行为,例如,AServiceImpl.barA()的调用或者BServiceImpl.barB(String _msg, int _type)抛出异常等行为。
  • 通知(Advice) :“切面”对于某个“连接点”所产生的动作,例如,TestAspect中对com.spring.service包下所有类的方法进行日志记录的动作就是一个Advice。其中,一个“切面”可以包含多个“Advice”,例如TestAspect
  • 切入点(Pointcut) :匹配连接点的断言,在AOP中通知和一个切入点表达式关联。例如,TestAspect中的所有通知所关注的连接点,都由切入点表达式execution(* com.spring.service.*.*(..))来决定
  • 目标对象(Target Object) :被一个或者多个切面所通知的对象。例如,AServcieImpl和BServiceImpl,当然在实际运行时,Spring AOP采用代理实现,实际AOP操作的是TargetObject的代理对象。
  • AOP代理(AOP Proxy) 在Spring AOP中有两种代理方式,JDK动态代理和CGLIB代理。默认情况下,TargetObject实现了接口时,则采用JDK动态代理,例如,AServiceImpl;反之,采用CGLIB代理,例如,BServiceImpl。强制使用CGLIB代理需要将 <aop:config>proxy-target-class 属性设为true

       通知(Advice)类型

  • 前置通知(Before advice) :在某连接点(JoinPoint)之前执行的通知,但这个通知不能阻止连接点前的执行。ApplicationContext中在<aop:aspect>里面使用<aop:before>元素进行声明。例如,TestAspect中的doBefore方法
  • 后通知(After advice) :当某连接点退出的时候执行的通知(不论是正常返回还是异常退出)。ApplicationContext中在<aop:aspect>里面使用<aop:after>元素进行声明。例如,TestAspect中的doAfter方法,所以AOPTest中调用BServiceImpl.barB抛出异常时,doAfter方法仍然执行
  • 返回后通知(After return advice) :在某连接点正常完成后执行的通知,不包括抛出异常的情况。ApplicationContext中在<aop:aspect>里面使用<after-returning>元素进行声明。
  • 环绕通知(Around advice) :包围一个连接点的通知,类似Web中Servlet规范中的Filter的doFilter方法。可以在方法的调用前后完成自定义的行为,也可以选择不执行。ApplicationContext中在<aop:aspect>里面使用<aop:around>元素进行声明。例如,TestAspect中的doAround方法。
  • 抛出异常后通知(After throwing advice) : 在方法抛出异常退出时执行的通知。 ApplicationContext中在<aop:aspect>里面使用<aop:after-throwing>元素进行声明。例如,TestAspect中的doThrowing方法。

       切入点表达式

  • 通常情况下,表达式中使用”execution“就可以满足大部分的要求。表达式格式如下:
Java代码 复制代码 收藏代码
  1. execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)  
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)

modifiers-pattern:方法的操作权限

ret-type-pattern:返回值

declaring-type-pattern:方法所在的包

name-pattern:方法名

parm-pattern:参数名

throws-pattern:异常

其中,除ret-type-pattern和name-pattern之外,其他都是可选的。上例中,execution(* com.spring.service.*.*(..))表示com.spring.service包下,返回值为任意类型;方法名任意;参数不作限制的所有方法。

  • 通知参数

可以通过args来绑定参数,这样就可以在通知(Advice)中访问具体参数了。例如,<aop:aspect>配置如下

Java代码 复制代码 收藏代码
  1. <aop:config>   
  2.     <aop:aspect id="TestAspect" ref="aspectBean">   
  3.         <aop:pointcut id="businessService"  
  4.             expression="execution(* com.spring.service.*.*(String,..)) and args(msg,..)" />   
  5.             <aop:after pointcut-ref="businessService" method="doAfter"/>   
  6.     </aop:aspect>   
  7. </aop:config>  
	<aop:config>
		<aop:aspect id="TestAspect" ref="aspectBean">
			<aop:pointcut id="businessService"
				expression="execution(* com.spring.service.*.*(String,..)) and args(msg,..)" />
				<aop:after pointcut-ref="businessService" method="doAfter"/>
		</aop:aspect>
	</aop:config>

TestAspect的doAfter方法中就可以访问msg参数,但这样以来AService中的barA()和BServiceImpl中的barB()就不再是连接点,因为execution(* com.spring.service.*.*(String,..))只配置第一个参数为String类型的方法。其中,doAfter方法定义如下:

Java代码 复制代码 收藏代码
  1. public void doAfter(JoinPoint jp,String msg)  
public void doAfter(JoinPoint jp,String msg)
  •   访问当前的连接点

任何通知(Advice)方法可以将第一个参数定义为 org.aspectj.lang.JoinPoint 类型。JoinPoint 接口提供了一系列有用的方法, 比如 getArgs() (返回方法参数)、getThis() (返回代理对象)、getTarget() (返回目标)、getSignature() (返回正在被通知的方法相关信息)和 toString() (打印出正在被通知的方法的有用信息。

 通知(Advice)类型

前置通知(Before advice) :在某连接点(JoinPoint)之前执行的通知,但这个通知不能阻止连接点前的执行。ApplicationContext中在<aop:aspect>里面使用<aop:before>元素进行声明。例如,TestAspect中的doBefore方法
后通知(After advice) :当某连接点退出的时候执行的通知(不论是正常返回还是异常退出)。ApplicationContext中在<aop:aspect>里面使用<aop:after>元素进行声明。例如,TestAspect中的doAfter方法,所以AOPTest中调用BServiceImpl.barB抛出异常时,doAfter方法仍然执行
返回后通知(After return advice) :在某连接点正常完成后执行的通知,不包括抛出异常的情况。ApplicationContext中在<aop:aspect>里面使用<after-returning>元素进行声明。
环绕通知(Around advice) :包围一个连接点的通知,类似Web中Servlet规范中的Filter的doFilter方法。可以在方法的调用前后完成自定义的行为,也可以选择不执行。ApplicationContext中在<aop:aspect>里面使用<aop:around>元素进行声明。例如,TestAspect中的doAround方法。
抛出异常后通知(After throwing advice) : 在方法抛出异常退出时执行的通知。 ApplicationContext中在<aop:aspect>里面使用<aop:after-throwing>元素进行声明。例如,TestAspect中的doThrowing方法。

 

 

在学习aop之前先来解释一下aop一些概念

  • Joinpoint:它定义在哪里加入你的逻辑功能,对于Spring AOP,Jointpoint指的就是Method。
  • Advice:特定的Jointpoint处运行的代码,对于Spring AOP 来讲,有Before advice、AfterreturningAdvice、ThrowAdvice、AroundAdvice(MethodInteceptor)等。
  • Pointcut:一组Joinpoint,就是说一个Advice可能在多个地方织入,
  • Aspect:实际是Advice和Pointcut的组合,但是Spring AOP 中的Advisor也是这样一个东西,但是Spring中为什么叫Advisor而不叫做Aspect。
  • Target:被通知的对象。
  • Proxy:将通知应用到目标对象后创建的对象
  • Weaving:将Aspect加入到程序代码的过程,对于Spring AOP,由ProxyFactory或者ProxyFactoryBean负责织入动作。



spring对AOP的支持有以下4种情况:

  • 经典的基于代理的aop(各版本spring)
  • @AspectJ注解驱动的切面(spring2.0后)
  • 纯pojo切面(spring2.0后)
  • 注入式AspectJ切面(各版本spring)



ITarget.java

Java代码 复制代码 收藏代码
  1. package com.myspring.aop;   
  2.   
  3. public interface ITarget {   
  4.   public void execute() throws TargetException;   
  5. }  
package com.myspring.aop;

public interface ITarget {
  public void execute() throws TargetException;
}



TargetImpl.java

Java代码 复制代码 收藏代码
  1. package com.myspring.aop;   
  2.   
  3. public class TargetImpl implements ITarget {   
  4.      
  5.   public TargetImpl() {   
  6.   }   
  7.       
  8.   public void execute() throws TargetException {   
  9.     System.out.println("main...");   
  10.   }   
  11. }  
package com.myspring.aop;

public class TargetImpl implements ITarget {
  
  public TargetImpl() {
  }
   
  public void execute() throws TargetException {
    System.out.println("main...");
  }
}



创建通知
Advice .java

Java代码 复制代码 收藏代码
  1. package com.myspring.aop;   
  2.   
  3. import java.lang.reflect.Method;   
  4.   
  5. import org.springframework.aop.AfterReturningAdvice;   
  6. import org.springframework.aop.MethodBeforeAdvice;   
  7. import org.springframework.aop.ThrowsAdvice;   
  8.   
  9. public class Advice implements MethodBeforeAdvice,   
  10.     AfterReturningAdvice, ThrowsAdvice {   
  11.   
  12.   public Advice() {}   
  13.        
  14.   public void before(Method method, Object[] args, Object target)    
  15.       throws Throwable {   
  16.     System.out.println("传统经典aop的before...");   
  17.   }   
  18.      
  19.   public void afterReturning(Object rtn, Method method,    
  20.       Object[] args, Object target) throws Throwable {   
  21.     System.out.println("传统经典aop的afterReturning...");   
  22.   }   
  23.      
  24.   public void afterThrowing(Throwable throwable) {   
  25.     System.out.println("传统经典aop的afterThrowing...");   
  26.   }   
  27.      
  28.   public void afterThrowing(Method method, Object[] args, Object target,    
  29.       Throwable throwable) {   
  30.       System.out.println("传统经典aop的afterThrowing2...");   
  31.   }   
  32.      
  33. }  
package com.myspring.aop;

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;

public class Advice implements MethodBeforeAdvice,
    AfterReturningAdvice, ThrowsAdvice {

  public Advice() {}
    
  public void before(Method method, Object[] args, Object target) 
      throws Throwable {
    System.out.println("传统经典aop的before...");
  }
  
  public void afterReturning(Object rtn, Method method, 
      Object[] args, Object target) throws Throwable {
    System.out.println("传统经典aop的afterReturning...");
  }
  
  public void afterThrowing(Throwable throwable) {
    System.out.println("传统经典aop的afterThrowing...");
  }
  
  public void afterThrowing(Method method, Object[] args, Object target, 
      Throwable throwable) {
	  System.out.println("传统经典aop的afterThrowing2...");
  }
  
}



TargetException .java

Java代码 复制代码 收藏代码
  1. package com.myspring.aop;   
  2.   
  3. @SuppressWarnings("serial")   
  4. public class TargetException extends RuntimeException {   
  5.   public TargetException() {}   
  6.      
  7.   public TargetException(String message) {   
  8.     super(message);   
  9.   }   
  10. }  
package com.myspring.aop;

@SuppressWarnings("serial")
public class TargetException extends RuntimeException {
  public TargetException() {}
  
  public TargetException(String message) {
    super(message);
  }
}



使用自动代理@AspectJ切面时,需要先注册一个切面AspectAdvice.java

Java代码 复制代码 收藏代码
  1. package com.myspring.aop;   
  2.   
  3. import org.aspectj.lang.annotation.After;   
  4. import org.aspectj.lang.annotation.AfterReturning;   
  5. import org.aspectj.lang.annotation.AfterThrowing;   
  6. import org.aspectj.lang.annotation.Aspect;   
  7. import org.aspectj.lang.annotation.Before;   
  8. import org.aspectj.lang.annotation.Pointcut;   
  9.   
  10. @Aspect//声明切面   
  11. public class AspectAdvice {   
  12.        
  13.     @Pointcut("execution(* *.execute(..))")//定义切点,匹配规则为(返回类型 返回类.方法(参数设置)   
  14.     public void todo(){}   
  15.        
  16.     @Before("todo()")   
  17.     public void before() {   
  18.         System.out.println("自动代理@AspectJ切面before...");   
  19.     }   
  20.        
  21.     @AfterReturning("todo()")   
  22.     public void afterReturning() {   
  23.         System.out.println("自动代理@AspectJ切面afterReturning...");   
  24.     }   
  25.        
  26.     @AfterThrowing("todo()")   
  27.     public void afterThrowing() {   
  28.         System.out.println("自动代理@AspectJ切面afterThrowing...");   
  29.     }   
  30.   
  31. }  
package com.myspring.aop;

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 AspectAdvice {
	
	@Pointcut("execution(* *.execute(..))")//定义切点,匹配规则为(返回类型 返回类.方法(参数设置)
	public void todo(){}
	
	@Before("todo()")
	public void before() {
		System.out.println("自动代理@AspectJ切面before...");
	}
	
	@AfterReturning("todo()")
	public void afterReturning() {
		System.out.println("自动代理@AspectJ切面afterReturning...");
	}
	
	@AfterThrowing("todo()")
	public void afterThrowing() {
		System.out.println("自动代理@AspectJ切面afterThrowing...");
	}

}


AdviceBean.java

Java代码 复制代码 收藏代码
  1. package com.myspring.aop;   
  2.   
  3. public class AdviceBean {   
  4.        
  5.     public void before() {   
  6.         System.out.println("纯POJO切面before...");   
  7.     }   
  8.        
  9.     public void afterReturning() {   
  10.         System.out.println("纯POJO切面afterReturning...");   
  11.     }   
  12.        
  13.     public void afterThrowing() {   
  14.         System.out.println("纯POJO切面afterThrowing...");   
  15.     }   
  16. }  
package com.myspring.aop;

public class AdviceBean {
	
	public void before() {
		System.out.println("纯POJO切面before...");
	}
	
	public void afterReturning() {
		System.out.println("纯POJO切面afterReturning...");
	}
	
	public void afterThrowing() {
		System.out.println("纯POJO切面afterThrowing...");
	}
}




applicationContext.xml

Xml代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
  4.     xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xmlns:p="http://www.springframework.org/schema/p"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd   
  7.     http://www.springframework.org/schema/aop    
  8.        http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">  
  9.        
  10.     <!-- 当定义一个纯粹的POJO切面时,创建此Bean -->  
  11.     <bean id="adviceBean" class="com.myspring.aop.AdviceBean"></bean>  
  12.     <!-- 利用spring AOP的配置元素定义一个通知 -->  
  13.     <aop:config>    
  14.         <!-- 引用刚才定义的一个纯粹的POJO切面Bean -->  
  15.         <aop:aspect ref="adviceBean">  
  16.         <!-- 定义一个命名切点,必点切点定义的重复,expression用于配置匹配规则,(返回类型 返回类.方法(参数设置) -->  
  17.         <aop:pointcut id="todo" expression="execution(* com.myspring.aop.TargetImpl.execute(..))" />     
  18.         <!-- 方法前通知 -->           
  19.         <aop:before method="before" pointcut-ref="todo" />           
  20.         <aop:after-returning method="afterReturning" pointcut-ref="todo" />      
  21.         <aop:after-throwing method="afterThrowing" pointcut-ref="todo"/>  
  22.     </aop:aspect>  
  23.   </aop:config>      
  24.   
  25.     <!-- ************************************** -->  
  26.     <bean id="aspectAdvice" class="com.myspring.aop.AspectAdvice"></bean>  
  27.     <!-- 当使用自动代理@AspectJ切面时,需要定义自动配置元素,在原来的xml文件的beans中加入xmlns:aop="http://www.springframework.org/schema/aop" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd,具体位置如上 -->  
  28.     <aop:aspectj-autoprox />  
  29.   
  30.     <!-- ************************************** -->      
  31.     <!-- 以下为传统的aop代理 -->  
  32.     <!-- 定义一个bean -->  
  33.     <bean id="target" class="com.myspring.aop.TargetImpl">  
  34.     </bean>  
  35.   
  36.     <!-- 定义一个通知bean -->  
  37.     <bean id="advice" class="com.myspring.aop.Advice">  
  38.     </bean>  
  39.        
  40.     <!-- 正则表达式切入点 -->  
  41.     <bean id="jdkRegexpAdvisor"      class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">  
  42.         <property name="advice" ref="advice" />  
  43.         <property name="pattern" value=".*execute" />  
  44.     </bean>  
  45.        
  46.     <!-- AspectJ切点 -->  
  47.     <bean id="aspectjPointcut" class="org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor">  
  48.         <property name="advice" ref="advice" /> <property name="expression"  
  49.         value="execution(* *.execute(..))" /> </bean>     
  50.     <!-- 使用ProxyFactoryBean工厂,用于生成一个代理,把一个或多个拦截者(和通知者)应用到Bean -->  
  51.     <bean id="myAop" class="org.springframework.aop.framework.ProxyFactoryBean">  
  52.         <property name="target" ref="target" />  
  53.         <property name="proxyInterfaces" value="com.myspring.aop.ITarget" />  
  54.         <property name="interceptorNames" value="jdkRegexpAdvisor" />  
  55.     </bean>  
  56.        
  57.     <!-- 创建自动代理,会自动检查通知者的切点是否匹配bean的方法,并且使用通知的代理来替换这个bean定义 -->  
  58.     <bean  
  59.         class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />  
  60. </beans>  
<?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:aop="http://www.springframework.org/schema/aop"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
	http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
	
	<!-- 当定义一个纯粹的POJO切面时,创建此Bean -->
	<bean id="adviceBean" class="com.myspring.aop.AdviceBean"></bean>
	<!-- 利用spring AOP的配置元素定义一个通知 -->
	<aop:config> 
		<!-- 引用刚才定义的一个纯粹的POJO切面Bean -->
		<aop:aspect ref="adviceBean">
		<!-- 定义一个命名切点,必点切点定义的重复,expression用于配置匹配规则,(返回类型 返回类.方法(参数设置) -->
		<aop:pointcut id="todo" expression="execution(* com.myspring.aop.TargetImpl.execute(..))" />	
		<!-- 方法前通知 -->	 	
		<aop:before method="before" pointcut-ref="todo" />		
		<aop:after-returning method="afterReturning" pointcut-ref="todo" />	
		<aop:after-throwing method="afterThrowing" pointcut-ref="todo"/>
    </aop:aspect>
  </aop:config>	

	<!-- ************************************** -->
	<bean id="aspectAdvice" class="com.myspring.aop.AspectAdvice"></bean>
	<!-- 当使用自动代理@AspectJ切面时,需要定义自动配置元素,在原来的xml文件的beans中加入xmlns:aop="http://www.springframework.org/schema/aop" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd,具体位置如上 -->
	<aop:aspectj-autoprox />

	<!-- ************************************** -->	
	<!-- 以下为传统的aop代理 -->
	<!-- 定义一个bean -->
	<bean id="target" class="com.myspring.aop.TargetImpl">
	</bean>

	<!-- 定义一个通知bean -->
	<bean id="advice" class="com.myspring.aop.Advice">
	</bean>
	
	<!-- 正则表达式切入点 -->
	<bean id="jdkRegexpAdvisor"		class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
		<property name="advice" ref="advice" />
		<property name="pattern" value=".*execute" />
	</bean>
	
	<!-- AspectJ切点 -->
	<bean id="aspectjPointcut" class="org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor">
		<property name="advice" ref="advice" /> <property name="expression"
		value="execution(* *.execute(..))" /> </bean>	
	<!-- 使用ProxyFactoryBean工厂,用于生成一个代理,把一个或多个拦截者(和通知者)应用到Bean -->
	<bean id="myAop" class="org.springframework.aop.framework.ProxyFactoryBean">
		<property name="target" ref="target" />
		<property name="proxyInterfaces" value="com.myspring.aop.ITarget" />
		<property name="interceptorNames" value="jdkRegexpAdvisor" />
	</bean>
	
	<!-- 创建自动代理,会自动检查通知者的切点是否匹配bean的方法,并且使用通知的代理来替换这个bean定义 -->
	<bean
		class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />
</beans>



TestSpringAop.java

Java代码 复制代码 收藏代码
  1. package com.myspring.aop;   
  2.   
  3. import org.springframework.context.ApplicationContext;   
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;   
  5.   
  6. public class TestSpringAop {   
  7.   public static void main(String[] args) {   
  8.     ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");   
  9.     //使用经典的aop   
  10.     ITarget target = (ITarget) ctx.getBean("myAop");   
  11.     //使用自动代理,可以直接调用目标对象   
  12.     ITarget autotarget = (ITarget) ctx.getBean("target");   
  13.     target.execute();   
  14.   }   
  15. }  

 

分享到:
评论

相关推荐

    springAOP实现数据字典.zip

    java springAOP实现数据字典

    AOP_With_Roslyn:罗斯林AOP

    转到您的解决方案文件夹运行 互联网 要自定义要在第一行和最后一行的每个方法处插入的内容,请参见 您可以将文档保存在解决方案的根目录中,然后执行 dotnet aop &lt;您的文件名&gt; 下表是通过集成了dotnet aop的...

    spring_aop4.rar_Home Home_jar 转换_spring AOP jar

    spring对AOP的支持 1、如果目标对象实现了接口,默认情况下会采用JDK的动态代理实现AOP 2、如果目标对象实现了接口,可以强制使用CGLIB实现AOP 3、如果目标对象没有实现了接口,必须采用CGLIB库,spring会自动在JDK...

    CCTR2012_V2.0_his2w5_EMC153转6060_V2_

    EMC153 aop 转 6060的 hex

    elasticsearch+Mybatis+Aop

    elasticsearch整合Mybatis,利用Mapper对ES进行DSL的调用,封装的工具类,aop负责返回值的类型转换

    springboot实现消息转换、切面AOP和Redis缓存

    springboot实现消息转换、切面AOP和Redis缓存,实现相关技术的实例,以及相关方法的使用说明

    PHP的AOP扩展Runkit.zip

    runkit提供了一套函数,能让你动态的修改任意类和函数的定义。...调用你设计的这个“钩子”,把所有的类的方法或函数都"钩"一遍,这样,不管是哪个方法在执行的时候,都会执行到你提供的切入点上的代码. ...

    AopSample:面向切片AOP示例

    AopSample 面向切片AOP示例 基于AOP 的两个库: 一个注解搞定安卓动态权限的所有复杂逻辑和兼容处理 一个注解搞定安卓线程转换 欢迎star

    AOP.rar_java aop_oracle

    对Oracle的JDBC进行重新封装,增加参数,进行字符集转换。

    关于spring的AOP ,IOC,DI的理解

    帮助初学者理解spring框架,有助于提高代码能力java.sql.SQLException: Duplicate entry '2' for key 'PRIMARY' Query: insert into ...) Parameters: [2, 6212999999999, 转出, 6000000, Wed May 17 07:51:00 CST 2017]

    weaverl:Erlang 遇到 AOP

    Weaverl 旨在为 Erlang 社区带来与主流语言(例如 /Java)中主要 AOP 框架提供的相似的 AOP 特性。 更具体地说,这个项目的目标是允许 Erlang/OTP 开发人员通过将横切关注点(例如日志记录)放入单独的文件(即模块...

    AOP for Erlang:Erlang的面向方面的编程(AOP)-开源

    针对Erlang的面向方面编程(AOP)的实现。 AOP编织器针对目标源文件集运行,并受方面定义控制。 编织器被实现为Erlang编译器的解析转换函数。

    AOP的实现机制.pdf

    1 AOP各种的实现 ............................................................................................................... 2 2 AOP里的公民 ...........................................................

    \\(^_^)/ 模拟Struts2的AOP实现 (转)

    NULL 博文链接:https://yanguz123.iteye.com/blog/2019701

    cglib,字节码生成库是生成和转换Java字节码的高级API。它被aop、测试、数据访问框架用来生成动态代理对象和拦截字段访问。.zip

    字节码生成库是生成和转换java字节码的高级api。

    aop各种能不能用的jar包.zip

    因为菜鸡兜兜转转下载了很多版本的,所以这里有可能有重复,请大家注意,不过只要保证版本之间不冲突,一般都可以的

    [JAVA SPRING AOP]aspectj-1.8.13.jar & aspectjrt-1.8.0.RELEASE.jar

    Spring 中基于 AOP 的 XML架构 所需要的jar文件. 网上找不到的同学可以在这里下载. 包括 aspectj-1.8.13.jar & aspectjrt-1.8.0.RELEASE.jar & aspectjweaver-1.8.0.RELEASE.jar & spring-aopalliance-1.0.jar四个...

    EL表达式(转)

    el表达式相关资料 表示式中第一个命名变量要么式一个隐式对象,要么是某个作用域(页面作用域、请求作用域、会话作用域或应用作用域)中的一个属性

    C#开源资源大汇总

    Encase 是C#编写开发的为.NET 平台提供的AOP 框架。Encase 独特的提供了把方面(aspects)部署到运行时代码,而其它AOP 框架依赖配置文件的方式。这种部署方面(aspects)的方法帮助缺少经验的开发人员提高开发效率。 ...

    java面试题

    spring使用AOP面向切面的思想进行事务管理的。 spring和Hibernate继承后,定义事务管理特性的时候查询为什么要定义为read-only? 答:因为添加、删除和更新都涉及到了数据库的修改,而查询并未涉及到数据库修改,...

Global site tag (gtag.js) - Google Analytics