基于XML实现AOP

首先创建切面类:LogAspect



编写XML文件:

<?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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!--基于XML配置版的AOP:
1)、将业务逻辑组件和切面类同时添加到容器中
 -->
 <bean id="mathCalculator" class="com.atguigu.impl.MyMathCalculator"></bean>
 
 <bean id="logAspect" class="com.atguigu.aspect.LogAspect"></bean>
<!--2)、告诉Spring哪些是切面类,并且切面类里面的这些方法何时运行:依赖aop名称空间 -->
<!-- aop:config:配置aop相关信息。都在这个标签体中配置 -->
 <aop:config>
  <!--指定一个全部切面都能引用的切入点表达式  -->
  <aop:pointcut expression="execution(* com.atguigu.impl.MyMathCalculator.*(..))" id="mypoint"/>
  <!-- ref:指定哪个组件是切面类:告诉了Spring哪些是切面类 -->
  <aop:aspect id="logAspect" ref="logAspect" order="11">
  <!--配置这个切面类的详细信息  -->
  <!-- 指定哪个方法是前置通知  
  pointcut:手写切入点表达式 
  pointcut-ref:引用外部的一个切入点表达式
  -->
  <aop:before method="logStart"  pointcut-ref="mypoint"/>
  <aop:after method="logEnd" pointcut="execution(* com.atguigu.impl.MyMathCalculator.*(..))"/>
  <!--  returning="result":指定接受返回值的参数名 -->
  <aop:after-returning method="logReturn" pointcut-ref="mypoint" returning="result"/>
  <!--  throwing="exception":指定接受异常的参数名-->
  <aop:after-throwing method="logException" pointcut-ref="mypoint" throwing="exception"/>
  </aop:aspect>
 </aop:config>
</beans>



编写MyMathCalculator类

public class MyMathCalculator {


public int add(int i, int j) {
int result = i + j;
System.out.println("方法内部...."+result);
return result;
}


public int sub(int i, int j) {
int result = i - j;
return result;
}


public int mul(int i, int j) {
int result = i * j;
return result;
}


public int div(int i, int j) {
int result = i / j;
System.out.println("除法执行");
return result;
}


}


猜你喜欢

转载自blog.csdn.net/qq_35423294/article/details/76461074