目录
本章学习源码Github地址:https://github.com/GuiZhouAndroid/MySpringAllProject/tree/master/SpringDemo09_AspectJ/src/main/java/com/dhrj/java/zsitking/around
环绕通知:通过拦截目标方法的方式 ,在目标方法前后增强功能的通知,是功能最强大的通知,一般事务使用此通知,此外环绕通知可以轻易的改变目标方法的返回值。
- public interface AroundService {
- //我的信息
- String myInfo(String name, int age);
- }
- @Service //Spring的IOC注解式创建业务逻辑层实例
- public class AroundServiceImpl implements AroundService {
- @Override
- public String myInfo(String name, int age) {
- System.out.println("myInfo(String name, int age)已执行...");
- return "我的个人信息 = 姓名:" + name + ",年龄:" + age;
- }
- }
- @Aspect //交给AspectJ的框架去识别切面类
- @Component //切面实例注册加载到spring容器中
- public class AroundAspectJ {
- /**
- * 环绕通知方法的规范
- * (1)访问权限是public
- * (2)切面方法有返回值,此返回值就是目标方法的返回值
- * (3)方法名称自定义
- * (4)方法有参数,此参数就是目标方法
- * (5)回避异常Throwable
- * (6)使用@Around注解声明是环绕通知
- * 参数:
- * value:指定切入点表达式
- */
-
- @Around(value = "execution(* com.dhrj.java.zsitking.around.impl.*.*(..))")
- public Object myAround(ProceedingJoinPoint pjp) throws Throwable {
- //1.前切功能实现
- System.out.println("环绕通知中的前置功能实现...");
- //2.目标方法调用——>重点调用
- Object obj = pjp.proceed(pjp.getArgs());//返回值obj即为目标方法的返回值,参数是目标方法的参数(有参数或无参数都不影响)
- //3.后切功能实现
- System.out.println("环绕通知中的后置功能实现...");
- return obj.toString() + ",环绕通知已修改此返回值"; //拦截目标方法并改变了目标方法的返回值
- }
- }
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
-
- <!--基于注解的访问要添加包扫描-->
- <context:component-scan base-package="com.dhrj.java.zsitking.around"/>
- <!--业务实现绑定AOP,默认是JDK动态代理,取时必须使用接口类型-->
- <aop:aspectj-autoproxy/>
- </beans>
- @Test
- public void testAround() {
- ApplicationContext ac = new ClassPathXmlApplicationContext("around/applicationContext.xml");
- AroundService aroundServiceImpl = (AroundService) ac.getBean("aroundServiceImpl");
- System.out.println("环绕通知最终返回值:" + aroundServiceImpl.myInfo("张松", 20));
- }

结论:@Around注解声明的方法在目标方法执行之前之后执行。被@Around注解为环绕增强的方法要有Object 类型返回值。并且方法可以包含一个ProceedingJoinPoint类型的参数。接口ProceedingJoinPoint其有一个proceed()方法,用于执行目标方法。若目标方法有返回值,则该方法的返回值就是目标方法的返回值。最后,环绕增强方法将其返回值返回。该增强方法实际是拦截了目标方法的执行。
仅自己学习记录,如有错误,敬请谅解~,谢谢~~~