配置实现
<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");
}
}