💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
**1.MyAdvice2 ** ~~~ public class MyAdvice2 { //处理连接点 public Object around(ProceedingJoinPoint pjp){ Object o = null; try{ System.out.println("环绕通知-前置"); o = pjp.proceed();//执行被代理对象方法 System.out.println("环绕通知-后置"); }catch(Throwable throwable){ throwable.printStackTrace(); System.out.println("异常通知"); }finally { System.out.println("环绕通知-最终"); } return o; } } ~~~ **2.配置信息** ~~~ <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"> <!--注册目标对象--> <bean name="userService" class="com.nobb.service.UserServiceImpl"></bean> <!--注册通知对象--> <bean name="myAdvice" class="com.nobb.advice.MyAdvice2"></bean> <aop:config> <!--定义切点--> <!--任意返回值 com.nobb.service 包下的任意 ServiceImpl结尾的 任意方法 任意参数--> <aop:pointcut id="myPC" expression="execution(* com.nobb.service.*ServiceImpl.*(..))"/> <aop:aspect ref="myAdvice"> <!--环绕切面:切点+环绕通知--> <aop:around method="around" pointcut-ref="myPC"/> </aop:aspect> </aop:config> </beans> ~~~ **3.测试代码** ~~~ package com.test; import com.nobb.service.UserService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext2.xml") public class AopDemo { //byName @Resource(name="userService") private UserService userService; @Test public void fun1(){ userService.save(); } } ~~~ **4.测试结果** 环绕通知-前置 save() 环绕通知-后置 环绕通知-最终