在上篇文章中( Spring(101)AspectJ框架開發(fā)AOP(基于xml))是使用xml對AspectJ的使用,@AspectJ 是AspectJ1.5新增功能,通過JDK5注解技術(shù),允許直接在Bean類中定義切面,所以可使用xml方式和注解方式來開發(fā)AOP 所以在這篇文章中我們使用注解來代替xml。
我們可使用注解1點1點替換xml的配置。
說明:
@Aspect 聲明切面,修飾切面類,從而取得 通知。
通知
@Before 前置
@AfterReturning 后置
@Around 環(huán)繞
@AfterThrowing 拋出異常
@After 終究
切入點
@PointCut ,修飾方法 private void xxx(){} 以后通過“方法名”取得切入點援用
在xml中
<!-- 創(chuàng)建目標類 -->
<bean id="userServiceId" class="com.scx.xmlproxy.test.UserServiceImpl"></bean>
<!-- 創(chuàng)建切面類(通知) -->
<bean id="myAspectId" class="com.scx.xmlproxy.test.MyAspect"></bean>
我們知道xml中的bean可使用注解@component來替換
在web開發(fā)中@component衍生了3個注解,我們也能夠為不同的層次使用不同的注解。
web開發(fā),提供3個@Component注解衍生注解(功能1樣)
@Repository :dao層
@Service:service層
@Controller:web層
這3個注解和@Component1樣,在web開發(fā)中使用這3個注解使代碼更加清晰明了。
替換結(jié)果以下:
對目標類,即service層
![]()
對切面類
<aop:aspect ref="myAspectId">
xml配置:
<aop:pointcut expression="execution(*com.scx.xmlproxy.test.*.*(..))" id="myPointCut"/>
注解替換:
需要在1個私有的方法上面添加注解@Pointcut。援用時就使用方法名稱pointCut。
xml配置:
<aop:before method="before" pointcut-ref="myPointCut"/>
注解替換:
在方法名上面添加@before注解
//前置通知
@Before(value = "pointCut()")
public void before(JoinPoint joinPoint){
System.out.println("MyAspect-before");
}
xml代碼
<aop:after method="after" pointcut-ref="myPointCut"/>
注解替換
//終究通知
@After(value="pointCut()")
public void after(JoinPoint joinPoint){
System.out.println("MyAspect-after");
}
xml配置:
<aop:after-returning method="afterReturning" pointcut-ref="myPointCut" returning="ret" />
注解替換:
//后置通知
@AfterReturning(value="pointCut()",returning="ret")
public void afterReturning(JoinPoint joinPoint,Object ret){
System.out.println("MyAspect-afterReturning "+joinPoint.getSignature().getName()+"\t"+ret);
}
xml配置:
<aop:around method="around" pointcut-ref="myPointCut"/>
注解替換:
//環(huán)繞通知
@Around(value = "pointCut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
System.out.println("MyAspect-around-前");
Object obj=joinPoint.proceed();//履行目標方法
System.out.println("MyAspect-around-后");
return obj;
}
xml配置:
<aop:after-throwing method="afterThrowing" pointcut-ref="myPointCut" throwing="e"/>
注解替換:
//異常通知
@AfterThrowing(value="pointCut()")
public void afterThrowing(JoinPoint joinPoint,Throwable e){
System.out.println("MyAspect-afterThrowing "+e.getMessage());
}
測試代碼和上篇1樣 運行結(jié)果也是1樣。