前提:该HelloWorld只是为了演示AOP在spring中的应用,通过schema风格的配置来讲解,配置到xml文件中,好处是可以更直观的对aop中连接点(Jointpoint),切入点(Pointcut),通知(Advice),切面(Aspect),引入(inter-type declaration),关注点,横切关注点等概念有更深入的了解
1.示例步骤和代码
1.1 编写业务逻辑关注点(切面)
package com.yang.learn.aop;
public class PayService {
public void save(){
System.out.println("save money");
}
public void withdraw(){
System.out.println("withdraw money");
}
}
1.2 编写业务逻辑织入横切关注点(通知)
package com.yang.learn.aop;
public class LogUtilAspect {
public void before(){
System.out.println("before execute method");
}
public void after(){
System.out.println("after execute method");
}
}
1.3 配置切面
<bean id="payService" class="com.yang.learn.aop.PayService" ></bean>
<!--
pointcut 是连接点的集合(切入点),Spring默认使用AspectJ语法
Aspect就是切面,被代理对象织入到Aspect
切面是连接点和通知以及织入的集合:通知+连接点+织入
-->
<bean id="logAspect" class="com.yang.learn.aop.LogUtilAspect"></bean>
<aop:config>
<aop:pointcut id="pointCut" expression="execution(* com.yang.learn..*.*(..))"></aop:pointcut>
<aop:aspect ref="logAspect">
<aop:before pointcut-ref="pointCut" method="before"></aop:before>
<aop:after pointcut-ref="pointCut" method="after"></aop:after>
</aop:aspect>
</aop:config>
1.4 编写测试代码
import com.yang.learn.aop.PayService;
import org.junit.Test;
import javax.annotation.Resource;
public class AopTest extends BaseTest{
@Resource
private PayService payService;
@Test
public void testAop(){
payService.save();
payService.withdraw();
}
}
1.5 测试结果展示
before execute method
save money
after execute method
before execute method
withdraw money
after execute method
从切面的配置可以更直观的了解到AOP中各个核心的概念
关注点:指一个模块,比如支付,交易,用户…
横切关注点:其实本质上跟关注点没什么区别,但是一般都作为织入的一点,比如日志,事务,统计… 业务作为被目标对象织入到横切关注点,通过动态代理来实现
连接点:Jointpoint,表示关注点上的一个织入连接点,比如方法入口
切入点:连接点的集合,通过AspectJ语法配置
通知:通知是横切关注点的组成部分,一般也是多个方法,但是织入的时机不同,包括前置,后置,和环绕通知
引入:可以在编译,加载,运行期间将横切关注点织入到关注点
切面:相当于通知在某个时候织入到某个切入点
被代理对象:一般就是关注点对象
AOP代理:spring使用JDK动态代理或者是cglib代理