KKB :spring中实现AOP:切点与切面(配置文件中)

1、配置项目环境

导入aop的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: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/aop
       http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">

添加jar包

<dependencies><dependency><groupId>aopalliance</groupId><artifactId>aopalliance</artifactId><version>1.0</version> </dependency>
 <dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId>
<version>1.8.13</version></dependency>
<dependency><groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId> <version>5.0.8.RELEASE</version>
</dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>5.0.8.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId>
<version>5.0.8.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId>
            <version>5.0.8.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId>
<version>5.0.8.RELEASE</version> </dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId>
            <version>5.0.8.RELEASE</version></dependency></dependencies>

2、创建项目原有的调取过程

service 调取 dao 的过程   application.xml中的基本配置为

    <bean id="udao" class="com.atshiyou.dao.Impl.UserDaoImpl"></bean>
    <bean id="uservice" class="com.atshiyou.service.impl.UserServiceImpl">
        <property name="dao" ref="udao"></property>
    </bean>

3、创建增强类,注意是创建一个类,里面写需要增强的方法

前置通知  aop:before 目标方法运行之前调用
后置通知(出现异常不会调用)aop : after-returning 在目标方法运行之后调用 
环绕通知  aop:around 在目标方法之前和之后都调用
最终通知(无论是否出现异常都会调用)aop:after 在目标方法运行之后调用
异常增强      aop:after-throwing 程序出现异常时执行(要求程序代码中不要处理异常)

 

 

比如,下面的例子MyAop中,就是写了三个切面方法,我们的AOP中的逻辑关系,与业务逻辑的代码的联系都是在配置文件.xml中实现的

配置文件中的aop配置

①首先将增强类对象加载进IOC容器

②建立增强类和目标方法之间的联系

  1. 首先需要明确,业务需求在哪加入增强配置,即切点
  2. 明确切点之后,将增强类的方法作为切面,“切”过去

找到切点(pointcut),插入切面(aspect),切面依赖于切点

补充——>环绕通知在类中如何定义

在增强类里的方法,不仅仅可以在执行目标方法的前后加上一些代码,我们还可以获取切点的信息

获取切点的信息 

输出结果:

除了上面这种通过jointPoint方式获取到切点的信息之外,我们还可以通过一个特殊的前置增强Advisor来获取到切点的信息

前置增强Advisor的使用

先创建一个单独的类,继承于  MethodBeforeAdvice

配置文件的配置:

执行结果:

猜你喜欢

转载自blog.csdn.net/awodwde/article/details/112812581