需要更多教程,微信扫码即可
后置通知:原始方法执行后执行,无论原始方法中是否出现异常,都将执行通知
应用:现场清理
aop:after
-
名称:aop:after
-
类型:标签
-
归属:aop:aspect标签
-
作用:设置后置通知
-
格式:
<aop:aspect ref="adviceId"> <aop:after method="methodName" pointcut="……"/> </aop:aspect>
-
说明:一个aop:aspect标签中可以配置多个aop:after标签
-
基本属性:
-
method :在通知类中设置当前通知类别对应的方法
-
pointcut :设置当前通知对应的切入点表达式,与pointcut-ref属性冲突
-
pointcut-ref :设置当前通知对应的切入点id,与pointcut属性冲突
-
后置通知配置
1.创建通知类
public class AOPAdvice {
public void after( ){
System.out.println("我是后置通知...");
}
}
创建UserServiceImpl类
public class UserServiceImpl implements UserService {
@Override
public void add(String name) {
System.out.println("add()执行了,name="+name);
}
}
2.修改spring配置文件,进行前置通知的配置
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--将所有进行AOP操作的资源加载到IoC容器中-->
<bean id="aopadvice" class="com.javaxxf.aop.AOPAdvice" />
<!--aop配置-->
<aop:config>
<aop:pointcut id="pt" expression="execution(* *..*(..))"/>
<!--配置切面-->
<aop:aspect ref="aopadvice">
<!--通知与切入点之间的关系-->
<aop:after method="after" pointcut-ref="pt" />
</aop:aspect>
</aop:config>
<!--配置service bean-->
<bean id="userService" class="com.javaxxf.service.Impl.UserServiceImpl"/>
</beans>
6.运行程序
public class UserController {
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService= (UserService) ac.getBean("userService");
userService.add("我爱学java");
//根据id查询user
}
}
结果:
后置通知获取执行方法的参数数据
和前置通知获取参数的方式一样,我这里不演示了。
后置通知获取执行方法的返回值
虽然这个是在目标执行方法后运行的,但是目标方法要是出现异常了,就不会执行这个后置通知了,所以程序也不能确定会不会出现异常,因为不确定性所以这个后置通知也是获取不了返回值的。
后置通知获取执行方法的异常信息
虽然这个是在目标执行方法后运行的,但是目标方法要是出现异常了,就不会执行这个后置通知了,所以程序也不能确定会不会出现异常,因为不确定性,所以这个后置通知也是获取不了执行方法的异常信息
Spring学习交流、资料领取。扫码即可哦!
文末福利
需要更多教程,微信扫码即可
别忘了扫码领取资料哦
【高清Java学习线路图】和【全套学习视频及相关资料】