spring中的环绕通知:它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式。
Spring框架为我们提供了一个接口: ProceedingJoinPoint。 该接口有一个方法proceed(),此方法就相当于明确调用切入点方法。该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会 为我们]提供该接口的实现类供我们使用。
用法:
package com.fy.utils;
import org.aspectj.lang.ProceedingJoinPoint;
public class logger {
public void printLog(){
System.out.println("Logger中的printLog开始记录日志了。。。");
}
public Object aroundPrintLog(ProceedingJoinPoint pjp){
Object rtValue = null;
try{
Object[] args = pjp.getArgs();//得到方法执行所需的参数
System.out.println("前置通知");
rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)
System.out.println("后置通知");
return rtValue;
}catch (Throwable t){
System.out.println("异常通知");
throw new RuntimeException(t);
}finally {
System.out.println("最终通知");
}
}
}
package com.fy.test;
import com.fy.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AOPTest {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
AccountService as = (AccountService)ac.getBean("accountService");
as.saveAccount();
}
}
<bean id="logger" class="com.fy.utils.logger"></bean>
<aop:config>
<aop:pointcut id="pt1" expression="execution(* com.fy.service.impl.*.*(..))"/>
<aop:aspect id="logAdvice" ref="logger">
<aop:around method="aroundPrintLog" pointcut-ref="pt1"></aop:around>
</aop:aspect>
</aop:config>
结果截图
**总结:**结合动态代理的环绕通知来理解,spring只是将其管理分配,你只需要告诉Spring是怎么回事就行。