java类
public class MyAspect {
public void before1() {
System.out.println("before1方法执行前增强");
}
public void before2() {
System.out.println("Before2 方法执行前增强");
}
public void before3() {
System.out.println("Before3方法执行前增强");
}
// public void before4(JoinPoint joinPoint) {
// System.out.println("---前置增强5开始");
// System.out.println("--要增强的类是"
// + joinPoint.getTarget().getClass().getName());
// // 判断此方法是否符合什么条件;getSingnature获取目标方法的参数
// if (!("Rose".equals(joinPoint.getSignature().getName()))) {
// throw new RuntimeException("您没有权限访问此方法");
// }
//
// }
// 后置方法增强;
// 参数一连接点,参数二,被增强方法的返回值 参数名要和xml中的returning参数名一致;
public void afterrunningAspectJ(JoinPoint joinPoint, Object returnVal) {
System.out.println("您发送短信的方法是:" + joinPoint.getSignature().getName());
System.out.println("您的余额是:" + returnVal);
}
// 环绕增强,在方法进行的前后都进行增强; 参数是正在执行的连接点
public Object aroundAspectJ(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("开启事务");
// 继续执行目标方法
Object object = joinPoint.proceed();
System.out.println("-事务结束");
// 放行
return object;
配图:
}
// 类发生异常通知;参数一连接点,参数二 异常ThrowAble类型
public void exceptionAspectJ(JoinPoint joinPoint, Throwable ex) {
System.out.println("发生异常的类--"
+ joinPoint.getTarget().getClass().getName() + "---发生异常的方法:"
+ joinPoint.getSignature().getName() + "---异常信息:"
+ ex.getMessage());
}
}
application xml对应配置
<bean id="customerService" class="cn.tt.service.CustomerService" />
<!-- 增强类 -->
<bean id="timeLogger" class="cn.tt.utils.RecoredMethodRunTimeAOP" />
<bean id="myAspectj" class="cn.tt.utils.MyAspect" />
<!-- 配置切入点和切面 -->
<!-- <aop:config> 对productService这个spring管理 的类进行 增强, 切入点是timeLogger <aop:pointcut
expression="bean(productService)" id="myPoint"/> 增强的类 被增强的点 <aop:advisor
advice-ref="timeLogger" pointcut-ref="myPoint"/> </aop:config> -->
<!-- AspectJ -->
<aop:config>
<!-- ref:增强类的引用 -->
<aop:aspect ref="myAspectj">
<aop:pointcut expression="within(cn.tt..*)" id="myPoint" />
<!-- <aop:before method="before1" pointcut-ref="myPoint" /> -->
<!-- <aop:before method="before2" pointcut-ref="myPoint"/> -->
<!-- <aop:before method="before3" pointcut-ref="myPoint"/> -->
<!-- <aop:before method="before4" pointcut-ref="myPoint"/> -->
<!-- <aop:after-returning method="afterrunningAspectJ" pointcut-ref="myPoint" returning="returnVal"/> -->
<aop:around method="aroundAspectJ" pointcut-ref="myPoint"/>
<!-- 必须配置异常信息,名字必须和方法中一致 -->
<aop:after-throwing method="exceptionAspectJ" pointcut-ref="myPoint" throwing="ex"/>
</aop:aspect>
</aop:config>
增强类参数和返回值;
通知类型 | 输入参数(可选) | 返回值类型 | 其他 |
Before前置通知 | JoinPoint(静态连接点信息) | void |
|
AfterReturning后置通知 | JoinPoint,Object | void |
|
Around环绕通知 | ProceedingJoinPoint(可执行的连接点信息) | Object | throws Throwable |
AfterThrowing抛出通知 | JoinPoint,Throwable | void |
|
After最终通知 | JoinPoint | void |
|