Spring 中各种通知

时间:2023-03-09 23:19:09
Spring 中各种通知
 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<!--
1、引入AOP的命名空间
xmlns:aop="http://www.springframework.org/schema/aop"
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
2、目标类
3、切面
4、拦截器 由spring内部实现
5、aop的配置
-->
<bean id="personDao" class="cn.test.aop.PersonDaoImpl"></bean>
<bean id="transaction" class="cn.test.aop.Transaction"></bean> <!-- aop配置 -->
<aop:config>
<!-- 切入点表达式
expression
确定哪个类可以生成代理对象
id 唯一标识 -->
<aop:pointcut expression="execution(* cn.test.aop.PersonDaoImpl.*(..))" id="perform"/>
<!-- 切面 -->
<aop:aspect ref="transaction">
<!-- 前置通知
* 在目标方法执行之前
-->
<aop:before method="beginTransaction" pointcut-ref="perform"/>
<!-- 后置通知
* 在目标方法执行之后
* 可以根据returning获取目标方法的返回值
* 如果目标方法遇到异常,该通知不执行
-->
<aop:after-returning method="commit" pointcut-ref="perform" returning="val"/>
<!-- 前置通知和后置通知只能在目标方法文中添加内容,但是控制不了目标方法的执行 -->
<!--
最终通知
* 在目标方法执行之后
* 无论目标方法是否遇到异常,都执行
* 经常做一些关闭资源
-->
<aop:after method="finallyMethod" pointcut-ref="perform"/>
<!--
异常通知
目的就是为了获取目标方法抛出的异常
-->
<aop:after-throwing method="exceptionMethod" throwing="ex" pointcut-ref="perform"/> </aop:aspect>
</aop:config> </beans>
 Transaction.java
1 public class Transaction {
//joinPoint 连接点信息
public void beginTransaction(JoinPoint joinPoint){
joinPoint.getArgs();//获取方法的参数
String methodName = joinPoint.getSignature().getName();
System.out.println(methodName);
System.err.println("begin trans action");
}
public void commit(JoinPoint joinPoint,Object val){
System.err.println("commit");
} public void finallyMethod(){
System.err.println("finally method");
} public void exceptionMethod(Throwable ex){
System.err.println(ex.getMessage());
} /**
* 环绕通知
* 能控制目标方法的执行
*/ public void aroundMethod(ProceedingJoinPoint joinPoint){
String methodName=joinPoint.getSignature().getName();
if("addPerson".equals(methodName)){ }
}

测试:

 /**
* 原理
* * 加载配置文件,启动spring容器
* * spring容器为bean创建对象
* * 解析aop的配置,会解析切入点表达式
* * 看纳入spring管理的那个类和切入点表达式匹配,如果匹配则会为该类创建代理对象
* * 代理对象的方法体的形成就是目标方法+通知
* * 客户端在context.getBean时,如果该bean有代理对象,则返回代理对象,如果没有代理对象则返回原来的对象
* 说明:
* 如果目标类实现了接口,则spring容器会采用jdkproxy,如果目标类没有实现接口,则spring容器会采用
* cglibproxy
*
* */
@Test
public void doSome(){ ApplicationContext applicationContext=new ClassPathXmlApplicationContext("cn/test/aop/applicationContext.xml");
PersonDao personDao= (PersonDao) applicationContext.getBean("personDao"); personDao.addPerson(); }