aop

来源:互联网 发布:如何设置淘宝客推广 编辑:程序博客网 时间:2024/06/10 22:35
1、AOP(面向切面,aspect-oriented-programming):纵向代码横向抽取

2、
joinpoint(连接点)
pointcut(切入点)
advice(通知/增强)
target(目标)
weaving(织入)
proxy(代理)
aspect(切面)

3、AOP思想名词
1)、准备连接点/切入点(测试代码)
2)、通知/增强代码(advice)
//前置通知
// |-目标方法运行之前调用
//后置通知(如果出现异常,不会调用)
// |-目标方法运行之后调用
//环绕通知:例如事务
@Around("execution(public void com.huida.aop.service.UserServiceImpl.insert())")
public Object around(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("环绕通知之前");
Object obj=pjp.proceed();
System.out.println("调用的方法");
System.out.println("环绕通知之后");
return obj;
}
// |-目标方法运行之前和之后都调用
//异常拦截通知
// |-目标方法出现异常的时候调用
//增强后置通知(无论是否出现异常都会被调用)
// |-目标方法运行之后调用

4、步骤
1)、导包
2)、配置约束
3)、准备目标对象
4)、准备通知类
前置通知
后置通知:如果出现异常就不执行
环绕通知:例如事务
异常拦截通知
增强后置通知:无论如何都执行
5)、配置文件,使用AOP
注入目标对象
注入通知对象
<aop:config>
<aop:pointcut id="切入点名称" expression="execution(切点表达式)"/>
<aop:aspect ref="通知对象名称">
<aop:before method="before" pointcut-ref="切入点名称"/>配置前置通知
....
</>
</>
6)、开启使用注解完成的嵌入(织入),自动生成代理
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
@Aspect指定当前类是通知类
@Pointcut抽取切点表达式,声明一个切入点
@Before前置通知类
@AfterReturning后置通知方法
@Around环绕通知方法
@AfterThrowing异常拦截方法
@After增强通知方法

5、配置aop面向切面
<!--配置目标对象 -->
<bean name="userSerice" class="com.huida.aop.service.UserServiceImpl"></bean>
<!--配置通知对象 -->
<bean name="myAdvice" class="com.huida.aop.service.MyAdvice"></bean>
1)、通过xml完成的嵌入
配置将通知织入对象
<aop:config>
<!-- expression="execution(public void com.huida.aop.service.UserServiceImpl.add())"
*com.huida.aop.service.UserServiceImpl.add()
*com.huida.aop.service.UserServiceImpl.*(..)所有的方法都织入对象
*com.huida.aop.*.UserServiceImpl.*(..)
通过通配符来规定哪些方法需要织入通知
-->
<!-- <aop:pointcut expression="execution(public void com.huida.aop.service.UserServiceImpl.insert())" id="hd009"/>
<aop:aspect ref="myAdvice">
指定名为before的方法作为前置通知,嵌入(织入)到目标类当中
<aop:before method="before" pointcut-ref="hd009"/>
后置
<aop:after-returning method="afterReturning" pointcut-ref="hd009"/>
环绕
<aop:around method="around" pointcut-ref="hd009"/>
异常拦截通知
<aop:after-throwing method="afterException" pointcut-ref="hd009"/>
增强后置通知
<aop:after method="after" pointcut-ref="hd009"/>
</aop:aspect>
</aop:config>
2)、开启使用注解完成的嵌入(织入),自动生成代理

<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
@Aspect放在类头上,把这个类作为一个切面。
@Before("execution(public void com.huida.aop.service.UserServiceImpl.insert())")前置通知

声明一个切入点
@Before("MyAdive.hd009()")
@Pointcut("execution(public void com.huida.aop.service.UserServiceImpl.insert())")
public void hd009(){}

原创粉丝点击