- xml配置
- 定义要被代理的方法的接口
public interface TestAop { public void print(String s); }
- 实现上述接口
public class TestAopImp implements TestAop{ public void print(String s) { System.out.println("具体业务逻辑"); } }
- 定义切面(要在被代理方法的前后进行的操作)
public class LogUtil { public void logbefore(JoinPoint joinPoint) { //joinPoint为代理的方法 System.out.println("业务处理之前记录日志"); } public void logAfter(JoinPoint joinPoint) { System.out.println("业务处理之后记录日志"); } // @Around("print()") // public void doAround(ProceedingJoinPoint pjp) throws Throwable { // System.out.println("开始处理业务"); //// pjp.proceed(); // System.out.println("处理业务结束"); // } //在处理的过程中发生异常 public void doAfterThrowing(Exception e) { System.out.println("例外通知:" + e); } public void doAfterReturning(Object result) { System.out.println("后置通知:" + result); } }
- xml文件中配置
<bean id="testAop" class="AOP.TestAopImp"/> <bean id="LogUtil" class="AOP.LogUtil"/> <aop:config> <aop:aspect id="aspect" ref="LogUtil"> <aop:pointcut id="PointtestAop" expression="execution(* AOP.TestAopImp.print*(..))"/> <aop:before method="logbefore" pointcut-ref="PointtestAop"/> <aop:after method="logAfter" pointcut-ref="PointtestAop"/> <!--<aop:around method="doAround" pointcut-ref="PointtestAop"/>--> <aop:after-returning method="doAfterReturning" pointcut-ref="PointtestAop" returning="result"/> <aop:after-throwing method="doAfterThrowing" throwing="e" pointcut-ref="PointtestAop"/> </aop:aspect> </aop:config>
2.注解配置
- 开启注解 在xml配置文件中加上<aop:aspectj-autoproxy/>
- 导包(不导包用不了注解)
<dependency> <groupId>aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.5.3</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency>
- 接口和实现类和xml配置相同,接下来定义切面
@Aspect public class LogUtil { @Pointcut("execution(* AOP.TestAopImp.print(String))") public void print() { } @Before("print()") public void logbefore(JoinPoint joinPoint) { //joinPoint为代理的方法 System.out.println("业务处理之前记录日志"); } @After("print()") public void logAfter(JoinPoint joinPoint) { System.out.println("业务处理之后记录日志"); } // @Around("print()") // public void doAround(ProceedingJoinPoint pjp) throws Throwable { // System.out.println("开始处理业务"); //// pjp.proceed(); // System.out.println("处理业务结束"); // } //在处理的过程中发生异常 @AfterThrowing(pointcut = "print()", throwing = "e") public void doAfterThrowing(Exception e) { System.out.println("例外通知:" + e); } @AfterReturning(pointcut = "print()", returning = "result") public void doAfterReturning(Object result) { System.out.println("后置通知:" + result); }
****************注意点****************
- around切点等于before切点加上after切点,使用的时候二者选其一 pjp.proceed()就等于执行被代理的函数
- 对于几个切点的执行顺序:
try
{
// 执行前置通知;
// 执行目标方法;
// 执行返回通知;
}
catche(Exception e)
{
// 执行异常通知;
}
finally
{
// 执行后置通知;
}