spring aop 常规使用

spring aop使用有两种方式,一种是基于XML的,一种是基于注解的,下面是使用例子:

 

一 基于XML的aop使用

1 定义一个切面类:

package main.daoImpl;

import org.aspectj.lang.JoinPoint;

public class LogAspect {

	public void before(JoinPoint jp) {
		System.out.println("Args:" + jp.getArgs());
		System.out.println("Kind:" + jp.getKind());
		System.out.println("Signature:" + jp.getSignature());
		System.out.println("Target:" + jp.getTarget());
		System.out.println("this:" + jp.getThis());
		System.out.println("正在进行权限校验!before...");
	}
	
	public void after() {
		System.out.println("结束调用!after...");
	}
	
	public void around() {
		System.out.println("环绕! around...");
	}
	
	public void doThrow() {
		System.out.println("抛异常!throw...");
	}
	
}

 2 定义一个目标类:

package main.daoImpl;

import main.dao.TestDao;

public class TestDaoImpl implements TestDao{

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

目标类实现TestDao接口,TestDao接口有一个抽象方法test()

 

3 在spring的配置文件中配置如下:

  <!-- 定义切面类和目标类 -->
  <bean id="logAspect" class="main.daoImpl.LogAspect"></bean>
  <bean id="testDaoImpl" class="main.daoImpl.TestDaoImpl"></bean>
  
  <!-- aop配置 -->
  <aop:config>  
    <!-- 配置切面 -->
    <aop:aspect id="aspectDao" ref="logAspect">
        <!-- 配置切入点 -->  
        <aop:pointcut id="logPointCut"  
            expression="execution(* main.daoImpl.*.*(..))" />  
        <!-- 定义通知和连接点 -->
        <aop:before pointcut-ref="logPointCut" method="before"/>  
        <aop:after pointcut-ref="logPointCut" method="after"/>  
        <aop:around pointcut-ref="logPointCut" method="around"/>  
        <aop:after-throwing pointcut-ref="logPointCut" method="doThrow" throwing="ex"/>  
    </aop:aspect>  
   </aop:config> 

4 测试代码:

	@Test
	public void test() {
		try {
			TestDao testDaoImpl = (TestDao)context.getBean("testDaoImpl");
			 System.out.println("===============" + testDaoImpl + "=======================");
			testDaoImpl.test();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			
		}
	}

 测试结果:

log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
===============main.daoImpl.TestDaoImpl@1d5a0=======================
Args:[Ljava.lang.Object;@14b5f4a
Kind:method-execution
Signature:void main.dao.TestDao.test()
Target:main.daoImpl.TestDaoImpl@1d5a0
this:main.daoImpl.TestDaoImpl@1d5a0
正在进行权限校验!before...
环绕! around...
结束调用!after...

二 基于Annotation的aop使用:

目标类还使用上面的TestDaoImpl.java;

1 定义切面类

package main.daoImpl;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class LogAnnotationAspect {
	
	@Pointcut("execution(* main.daoImpl.*.*(..))")
	public void allMethod() {
		
	}

	@Before("allMethod()")
	public void before(JoinPoint jp) {
		System.out.println("Args:" + jp.getArgs());
		System.out.println("Kind:" + jp.getKind());
		System.out.println("Signature:" + jp.getSignature());
		System.out.println("Target:" + jp.getTarget());
		System.out.println("this:" + jp.getThis());
		System.out.println("正在进行权限校验!before...");
	}
	
	@After("allMethod()")
	public void after() {
		System.out.println("结束调用!after...");
	}
	
	@Around("allMethod()")
	public void around() {
		System.out.println("环绕! around...");
	}
	
	@Around("allMethod()")
	public void doThrow() {
		System.out.println("抛异常!throw...");
	}
	
}

 2 spring配置文件中配置:

  <!-- 启动对aspectJ注解的支持 -->
  <aop:aspectj-autoproxy/>
  <!-- 定义切面类,目标类 -->
  <bean id="logAnnotationAspect" class="main.daoImpl.LogAnnotationAspect"></bean>
  <bean id="testDaoImpl" class="main.daoImpl.TestDaoImpl"></bean>

 3 测试代码和上面的测试代码一直,测试结果一致!

 

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“就可以满足大部分的要求。表达式格式如下:
       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>  

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

Java代码   收藏代码
任何通知(Advice)方法可以将第一个参数定义为 org.aspectj.lang.JoinPoint 类型。JoinPoint 接口提供了一系列有用的方法, 比如 getArgs() (返回方法参数)、getThis() (返回代理对象)、getTarget() (返回目标)、getSignature() (返回正在被通知的方法相关信息)和 toString() (打印出正在被通知的方法的有用信息。
(aop概念部分摘抄自:http://www.iteye.com/topic/336873)
 
JoinPoint的api文档:http://www.eclipse.org/aspectj/doc/released/runtime-api/org/aspectj/lang/JoinPoint.html
 三 spring aop 自动代理
1 定义接口:
package main.aop;

public interface Target {

	public void target();
}
 2 目标类:
public class TargetA implements Target {

	public void target() {
		System.out.println("targetA is executing!");
	}

}
 3 前置通知类:
public class BeforeAdvice implements MethodBeforeAdvice {

	public void before(Method method, Object[] arg1, Object arg2)
			throws Throwable {
		System.out.println(method);
		for (Object obj : arg1) {
			System.out.println(obj);
		}
		System.out.println(arg1);
		System.out.println(arg2);
	}

}
 4 spring配置:
  <!-- 定义目标类和前置通知类--> 
  <bean id="targetA" class="main.aop.TargetA"></bean>
  <bean id="beforeAdvice" class="main.aop.BeforeAdvice"></bean>
  
   <!-- 定义自动代理类 -->
   <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">  
       <!-- 引入被自动代理的目标类 -->
       <property name="beanNames">  
           <list>  
               <value>target*</value>  
           </list>  
       </property>  
       <!-- 引入通知 -->
       <property name="interceptorNames">  
           <list>  
               <value>beforeAdvice</value>  
           </list>  
       </property>  
   </bean>  
 5 测试代码:
	@Test
	public void test() throws URISyntaxException {
		Target targetA = (Target)context.getBean("targetA");
		targetA.target();
	}
 测试结果:
public abstract void main.aop.Target.target()
[Ljava.lang.Object;@402af3
main.aop.TargetA@18d7ace
targetA is executing!
本人感觉自动代理不如自己配置或注解的aop切面编程灵活和强大,所以暂时写一个自动代理的demo,如有需要的时候继续深入!

  

猜你喜欢

转载自abc08010051.iteye.com/blog/1974709