Spring(5) -(15)使用Xml开发AOP

2018-09-26  本文已影响5人  小白201808

一.了解AOP相关的术语的概念

  1.Aspect:切面:pointcut +advice
  (去哪写地方+在什么时机+做什么增强)
  
  2.pointcut:切入点,需要在哪些包中的哪些类中哪些方法上做增强(joinpoint的集合)
  
  3.joinpoint:要增强的方法(where:去哪里做增强操作)
  
  4.Advice:增强(通知)当拦截到joinpoint之后,在方法执行的某个时机做什么样的增强操作
  
  方法执行时机:前置增强
              后置增强
              异常增强
              最终增强
              环绕增强
  5.targer:目标对象,被代理的目标对象,委托对象
  6.weaving:织入 把advice加到targer上被创建出代理对象的过程(Spring帮我们完成)
  7.proxy:一个类被AOP织入增强后,创建出来的代理对象。

二.使用Xml开发AOP

 1. 加入依赖的jar包
 2. 配置
 3. 使用CGLIB的方式

1. 加入依赖的jar包

  spring-aop-版本.RELEASE.jar
  com.springscoure.org-aopalliance-1.0.0.jar
  com.springsource.org.aspectJ.weaver-s.6.8.RELEASE.jar
  ⚠️:spring5 开始在spring-aop库中纳入AOP联盟的API,不再需要拷贝 aopalliance-1.0.0.jar

2.配置(代码演示)

   1.添加aop名字空间
   2.配置AOP(3W what + where + when)
<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- di注解解析器 -->
<!--  <context:annotation-config/> -->

<!--IOC注解解析器  -->
<!-- <context:component-scan base-package="com.keen.proxy"/> -->
<bean id = "employeeDAO" class = "com.keen.proxy.dao.EmployeeDAOimpl"/>


 <!-- employeeService -->
 <bean id = "employeeService" class ="com.keen.proxy.service.IEmployeeServiceImpl">
     <property name = "dao" ref = "employeeDAO"/>
</bean>


<bean id = "txManager" class = "com.keen.proxy.tx.TransactionManager"/>
<!--配置AOP:在什么地方+什么时机+做什么 -->

<aop:config proxy-target-class="false"><!-- 采用AOP动态机制(默认机制)当改为false,就是CDGLIB机制) -->
<!-- 配置切面 -->
    <!-- What,做什么增强 eg:做事务增强 -->
    <aop:aspect ref = "txManager"><!-- 关联what -->
       <!-- 2.where:在哪些包中的哪些类中的哪些方法上做增强 -->
       <aop:pointcut id="txPoint"
            expression="execution(* com.keen.proxy.service.*Service.*(..))" />
       <!-- 3. when :在什么时候执行增强 --> 
       <aop:before method = "begin" pointcut-ref ="txPoint"/>
       <aop:after-returning method="commit" pointcut-ref = "txPoint"/>
       <aop:after-throwing method="rollback" pointcut-ref = "txPoint"/>
    </aop:aspect>
</aop:config>


</beans>

上一篇下一篇

猜你喜欢

热点阅读