环绕通知无参与ProceedingJoinPoint接口:方法的前后进行环绕,但是与
@before
和@after
不同的是,他无法知道下面代码中的环绕前方法
是否是在前置位置,后置同理,于是要在方法中添加参数ProceedingJoinPoint proce
并且要在两个输出语句中间调用方法proceed()
,别忘了抛出异常
环绕方法:
@Around("pt()")public void around(ProceedingJoinPoint proce) throws Throwable {System.out.println("环绕前方法");proce.proceed();System.out.println("环绕后方法");}
环绕有参时: 切入点中的
execution()
中的参数变化:返回形和切入点所指的类的方法返回型一致,注意execution()
里面的方法后面的括号里可能要定义int``String
之类的,这个也是和切入点所指的类保持一致
@Pointcut("execution(int com.itjh.pojo.Dao.select(int))")private void pt(){}
环绕方法:方法的返回类型同一写成Object型
@Around("pt()")public Object around(ProceedingJoinPoint proce) throws Throwable {System.out.println("环绕前方法");int i=(int)proce.proceed();System.out.println("环绕后方法");return i;}
测试类:接收环绕方法传回来的值,打印:
import com.itjh.pojo.Dao;
import com.itjh.springaopconfig.AopConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class TestAop01 {public static void main(String[] args) {ApplicationContext applicationContext =new AnnotationConfigApplicationContext(AopConfig.class);Dao aop =applicationContext.getBean(Dao.class);aop.select(100);}
}
环绕需注意:
成功运行后后置:@AfterRunning
发生异常后输出:@AfterThrowing:产生异常后后置