Java框架------Spring框架AOP注解(@Aspect和@Around)
AOP 中的声明主要有两种基于XML和基于Annotation
之前的为借助xml ,现在介绍⼀下借助注解的⽅式,修改之前的⼩项⽬
常见五种通知类型
org.springframework.aop.MethodBeforeAdvice(前置通知)在⽅法之前⾃动执⾏的通知称为前置通知,可以应⽤于权限管理等功能。
org.springframework.aop.AfterReturningAdvice(后置通知)在⽅法之后⾃动执⾏的通知称为后置通知,可以应⽤于关闭流、上传⽂件、删除临时⽂件等功能。
org.aopalliance.intercept.MethodInterceptor(环绕通知)在⽅法前后⾃动执⾏的通知称为环绕通知,可以应⽤于⽇志、事务管理等功能。
org.springframework.aop.ThrowsAdvice(异常通知)在⽅法抛出异常时⾃动执⾏的通知称为异常通知,可以应⽤于处理异常记录⽇志等功能。
org.springframework.aop.IntroductionInterceptor(引介通知)在⽬标类中添加⼀些新的⽅法和属性,可以应⽤于修改旧版本程序(增强类)。
常见注解
@Aspect:作⽤是把当前类标识为⼀个切⾯供容器读取
@Around:环绕增强,相当于MethodInterceptor
@AfterReturning:后置增强,相当于AfterReturningAdvice,⽅法正常退出时执⾏
@Pointcut:Pointcut是植⼊Advice的触发条件。每个Pointcut的定义包括2部分,⼀是表达式,⼆是⽅法签名。⽅法签名必须是 public及void型。可以将Pointcut中的⽅法看作是⼀个被Advice引⽤的助记符,因为表达式不直观,因此我们可以通过⽅法@Before:标识⼀个前置增强⽅法,相当于BeforeAdvice的功能,相似功能的还有
@AfterThrowing:异常抛出增强,相当于ThrowsAdvice
@After: final增强,不管是抛出异常或者正常退出都会执⾏使⽤pointcut代码
@DeclareParents ⽤于定义引介通知,相当于IntroductionInterceptor(不要求掌握)。
⼀、借助注解实现之前⼩例⼦
1、对bean 的注解,借助@Component
将l 中的
<bean name="ser_stu"class="com.obge.service.StudentService"></bean>
<bean name="logAspect"class="com.obge.aspect.LogAspect"/>
变成如下,表⽰扫描aspect 和service 两个包,定位业务层和切⾯类
<context:component-scan base-package="com.obge.aspect"/>
<context:component-scan base-package="com.obge.service"/>
在相关包中的类上加上Component 注解
2、对切⾯的注解,借助 @Aspect 和 @Around
@Aspect 注解表⽰这是⼀个切⾯
@Around(value = "execution(* com.obge.service.StudentService.*(..))") 表⽰对com.obge.service.StudentService这个类中的所有⽅法进⾏切⾯操作
将l 中的
<aop:config>
<!--
* 返回任意类型
(..) 参数是任意数量和类型
-->
<aop:pointcut  id="alog_pointcut" expression="execution(* com.obge.service.StudentService.*(..))"/>
<aop:aspect id="asp_log"ref="log_Aspect">
<aop:around pointcut-ref="alog_pointcut" method="log"/>
</aop:aspect>
</aop:config>
替换为,到注解的切⾯类,进⾏切⾯配置
<aop:aspectj-autoproxy/>
切⾯类中进⾏如下修改:
package com.obge.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
//bean 对象
@Component("log_Aspect")
//⼀个切⾯类
@Aspect
public class LogAspect {
//将这个⽅法与 StudentService 类中的⽅法进⾏编制
@Around(value="execution(* com.obge.service.StudentService.*(..))")
public Object log(ProceedingJoinPoint proJoinPoint) throws Throwable {
System.out.println("开始记录⽇志:"+Signature());
Object obj = proJoinPoint.proceed();
spring aop应用场景System.out.println("⽇志结束:"+Signature().getName());
return obj;
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。