AOP面向切面编程,与OOP是不同的两种概念,他们之间的关系并不是矛盾的,可以说是相铺相成的,OOP是从静态的形式上来考虑程序,而AOP是从动态,程序运行的时候进行改变程序的。Spring借鉴的是aspectJ的思想,谈到AOP有几个重要的概念是必须要提的。
切面(Aspect):业务流程中某个特定的步骤
连接点(JoinPoint):程序执行过程中明确的点,比如方法的调用,异常的抛出,spring AOP 中只是值方法的调用
增强处理(Advice):aop在特定的切入点执行的增强处理,一般有Around,before,after,afterReturning等
切入点(pointcut):可以插入增强处理的连接点。
以下是通过注解方式生成的一些处理代码。
需要在spring的配置文件加入如下代码
<aop:aspectj-autoproxy/>
相关java代码
-
package test;
-
-
import java.util.Arrays;
-
-
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.Around;
-
import org.aspectj.lang.annotation.Before;
-
-
public class AroundTest {
-
/**
-
* 定义环绕通知,其中excution 是关键词,test.*.*(..)代表着test包下的所有类的所有方法
-
* @param pr
-
* @return
-
* @throws Throwable
-
*/
-
@Around("execution(* test.*.*(..))")
-
public Object around(ProceedingJoinPoint pr) throws Throwable{
-
System.out.printf("excute method before");
-
Object rvt = pr.proceed(new String[]{"被改变的命运"});
-
System.out.printf("excute method after");
-
return rvt+"新增的内容";
-
-
}
-
/**
-
* Object [] getArgs();返回执行目标时的参数
-
* Signature getSignature():返回被增强的方法的相关信息
-
* Object getTarget();返回被植入增强处理的目标对象
-
* Object getThis();返回AOp框架为目标对象生成的代理对象
-
* @param jp
-
* @return
-
*/
-
@Before("execution(* test.*.*(..))")
-
public void before(JoinPoint jp){
-
System.out.println("Before增强:模拟执行全线检查");
-
System.out.println("Before增强:被植入增强目标的方法为:"
-
+jp.getSignature().getName()
-
);
-
System.out.println("Before增强:目标方法的参数为:"+Arrays.toString(jp.getArgs()));
-
-
}
-
@AfterReturning(pointcut="excution(* test.*.*(..))",returning="ob")
-
public void afterReturn(JoinPoint jp,Object ob){
-
-
System.out.println("AfterReturnning增强:获取目标方法返回值"+ob);
-
System.out.println("AterReturnning增强:模拟记日志功能"
-
+jp.getSignature().getName()
-
);
-
System.out.println("Before增强:目标方法的参数为:"+Arrays.toString(jp.getArgs()));
-
}
-
@After("execution(* test.*.*(..))")
-
public void after(JoinPoint jp){
-
-
System.out.println("After增强:获取目标方法返回值");
-
System.out.println("Ater增强:模拟释放资源"
-
+jp.getSignature().getName()
-
);
-
-
}
-
-
}
运行过程可以看到around先执行,然后调用before执行,紧接着around执行,再然后afterReturnning,最后执行after。同样也可以采用配置文件来进行管理。在配置文件中定义切点的时候都必须在 《config>
-
<aop:config>
-
-
</aop:config>标签内配置
-
<aop:config>
-
<!-- 定义一个切面类 -->
-
<aop:aspect id="afterForAspect" ref="afterAspcet">
-
<!-- 配置增强处理的时候 其中 pointcut置顶切入的表达式,pointcut-ref指定一个已经定义好的切入点
-
method 指定 切入的方法的名称,throwing该属性只对<aop:throwing/>有效,returning只对
-
<aop:after-returning/>有效
-
-->
-
<aop:before pointcut="execution(* test.HibernateTest.test(..))" method="before"/>
-
<aop:after pointcut="execution(* test.HibernateTest.test(..))" method="after" />
-
<!-- <aop:around method="around" pointcut="execution(* test.HibernateTest.test(..))"/> -->
-
<aop:after-returning method="afterReturn" pointcut="execution(* test.HibernateTest.test(..))" returning="ob"/>
-
</aop:aspect>
-
</aop:config>
阅读(1276) | 评论(0) | 转发(0) |