配置實現
<bean id="userService" class="com.spring.test6_aopAspectJ.UserServiceImpl"></bean>
<bean id="myAspect" class="com.spring.test6_aopAspectJ.MyAspect"></bean>
<aop:config>
<aop:aspect ref="myAspect">
<aop:pointcut expression="execution(* com.spring.test6_aopAspectJ.UserServiceImpl.*(..))" id="myPointCut"/>
<!-- 前置通知配置 -->
<!-- <aop:before method="myBefore" pointcut-ref="myPointCut"/> -->
<!-- 後置通知 -->
<!-- <aop:after-returning method="afterReturning" pointcut="execution(* com.spring.test6_aopAspectJ.UserServiceImpl.*(..))"/> -->
<!-- 環繞通知 -->
<!-- <aop:around method="arount" pointcut-ref="myPointCut" arg-names="pjp"/> -->
<!-- 異常通知 -->
<!-- <aop:after-throwing method="afterThrowing" pointcut-ref="myPointCut"/> -->
<!-- 最終通知 -->
<aop:after method="after" pointcut-ref="myPointCut"/>
</aop:aspect>
</aop:config>
在環繞通知方法的中必須要傳入參數,而且這個參數必須是org.aspectj.lang.JoinPoint的實現類ProceedingJoinPoint,並且參數如果不是myJoinPoint的情況下,在xml配置環繞通知時,需要知道參數名arg-names="參數名",並且環繞通知方法必須返回一個Object對象。在方法體通過proceed方法放行目標方法。
public class MyAspect {
public void myBefore(JoinPoint jp){
System.out.println("before:"+jp.getSignature().getName());
}
public void afterReturning(JoinPoint jp){
System.out.println("afterReturning:"+jp.getSignature().getName());
}
public Object arount(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("around:1");
Object obj = pjp.proceed();
System.out.println("around:2");
return obj;
}
public void afterThrowing(){
System.out.println("afterThrowing");
}
public void after(JoinPoint jp){
System.out.println("after");
}
}
註解實現
<context:component-scan base-package="com.spring.test7_aopAspectJAnno"></context:component-scan>
<!-- <context:annotation-config></context:annotation-config> -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
@Component
@Aspect
public class MyAspect {
@Pointcut("execution(* com.spring.test7_aopAspectJAnno.UserService.*(..))")
private void myPointCut(){
}
// @Before("execution(* com.spring.test7_aopAspectJAnno.UserService.*(..))")
public void myBefore(JoinPoint jp){
System.out.println("before:"+jp.getSignature().getName());
}
@AfterReturning(value="myPointCut()",returning="obj")
public void afterReturning(JoinPoint jp,Object obj){
System.out.println("afterReturning:"+jp.getSignature().getName());
}
// @Around("execution(* com.spring.test7_aopAspectJAnno.UserService.*(..))")
public Object arount(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("around:1");
Object obj = pjp.proceed();
System.out.println("around:2");
return obj;
}
// @AfterThrowing(value="execution(* com.spring.test7_aopAspectJAnno.UserService.*(..))",throwing="e")
public void afterThrowing(JoinPoint jp,Throwable e){
System.out.println("afterThrowing"+e.getMessage());
}
// @After("execution(* com.spring.test7_aopAspectJAnno.UserService.*(..))")
public void after(JoinPoint jp){
System.out.println("after");
}
}