spring-aop基础搭建

下载spring-framework-3.0.2.RELEASE-dependencies.zip与spring-framework-4.2.4.RELEASE-dist.zip文件

解压后

spring-aop基础搭建

然后去里面找下面几个jar包,这个只配置aop,所有jar包导入的知识aop需要的。

spring-aop基础搭建

导入jar包。


配置

导入aop约束,spring约束(不会配置约束的去网上找找,配不成功的给我留言)

spring-framework-4.2.4.RELEASE-dist\spring-framework-4.2.4.RELEASE\schema

spring-aop-4.2.xsd

spring-beans-4.2.xsd


写一个接口与实现类,

spring-aop基础搭建

spring-aop基础搭建

写一个要切入的代码

spring-aop基础搭建

配置

spring-aop基础搭建

<!-- 导入约束,aop,beans -->
  <!-- 配置目标对象 -->
  <bean name="userServiceTarget" class="com.mask.service.UserServiceImpl"></bean>
  <!-- 配置通知对象 -->
  <bean name="myAdvice" class="com.mask.a_srpingaop.MyAdvice"></bean> 
  <!-- 配置将通知织入目标对象 -->
  <aop:config>
    <!-- 配置切入点 -->
    <!-- expression="excution(com.mask.service.UserService.save()) "
         //公开的返回值也为空的空参方法
         public void com.mask.service.UserService.save()
         //public可以省略 默认public void改为*,因为对返回值没有要求
         * com.mask.service.UserService.save()
         //为UserService类下的所有方法切入,方法还是空参的
         * com.mask.service.UserService.*()
         //为UserService类下的所有方法切入,参入没有要求,也可以为空
         * com.mask.service.UserService.*(..)
          //为*Service后缀类下的所有方法切入,参入没有要求,也可以为空,用这个就可以了
         * com.mask.service.*Service.*(..) 
         //service。。不但找已*Service为后缀的,还会找com.mask.service下的所有子包。。。一般用不到。
         * com.mask.service.。*Service.*(..) 
    -->
    <aop:pointcut expression="execution(* com.mask.service.*Service.*(..))" id="pc"/>
    <aop:aspect ref="myAdvice">
      <!-- 前置通知方法
      com.mask.a_srpingaop.MyAdvice里的before方法作为前置通知
                    。。。
       -->
      <aop:before method="before" pointcut-ref="pc"/>
      <!-- 后置 -->
      <aop:after-returning method="afterReturning" pointcut-ref="pc"/>
      <!-- 环绕 -->
      <aop:around method="around" pointcut-ref="pc"/>
      <!-- 后置 -->
      <aop:after method="after" pointcut-ref="pc"/>
      <!-- 异常 -->
      <aop:after-throwing method="afterException" pointcut-ref="pc"/>
      
    </aop:aspect>

  </aop:config>


写一个测试方法

spring-aop基础搭建

  运行测试方法,双击测试方法名 然后Run As->JUnit Test 测试结果

spring-aop基础搭建

----------------------------------------------------------------------------------------------------------------------------------

下面使用注解的方式配置。

把上面的applicationContext.xml文件的<aop:config></aop:config>干掉换成自动配置

<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

spring-aop基础搭建

然后在配置通知对象里写注解

spring-aop基础搭建

spring-aop基础搭建

注解后直接写切面表达式出现硬编码问题,优化为

spring-aop基础搭建

spring-aop基础搭建

测试结果

spring-aop基础搭建