Spring配置文件中使用aop

Spring配置文件中使用aop applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" 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-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd ">

<!-- 1.目标对象 -->

<bean name="userService" class="cn.example.service.UserServiceImpl" ></bean>

<!-- 2.通知对象 -->

<bean name="myAdvice" class="cn.example.d_springaop.MyAdvice" ></bean>

<!-- 3.把目标对象设置到切点 -->

<aop:config>

<aop:pointcut expression="execution(*cn.example.service.*ServiceImpl.*(..))" id="pc"/>

  <!-- 3.给目标对象设置切面:即给目标对象的指定方法执行前后,要插入执行的方法 -->

<aop:aspect ref="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-throwing method="afterException" pointcut-ref="pc"/>

<!-- 后置 -->

<aop:after method="after" pointcut-ref="pc"/>

</aop:aspect>

</aop:config>

</beans>

 

aop:pointcut标签:

  expression属性:设置目标方法

              语法: expression="execution(目标方法的群路径)"

目标方法全路径的写法:

1.  public void cn.example.service.UserServiceImpl.save() //一个完整的方法路径

2.  void cn.example.service.UserServiceImpl.save() //省略默认的public

3.  * cn.example.service.UserServiceImpl.save() //返回类型不要求 用*取代

4.  * cn.example.service.UserServiceImpl.*() //对象方法全设为目标方法 用*取代

5.  * cn.example.service.UserServiceImpl.*(..) //方法的参数不作要求 用..表示

6.  * cn.example.service.*ServiceImpl.*(..) //所有以ServiceImpl结尾类名 *ServiceImpl表示

7.  * cn.example.service..*ServiceImpl.*(..) //cn.example.service包下的所有子包也包过在内加入.表示

 

Spring配置文件中使用aop通知类(目标方法执行前后要执行的代码所在类):

public class MyAdvice {

//前置通知:目标方法运行之前调用

public void before(){

System.out.println("这是前置通知!!");

}

//后置通知:在目标方法运行之后调用

public void afterReturning(){

System.out.println("这是后置通知(如果出现异常不会调用)!!");

}

//环绕通知:在目标方法之前和之后都调用

public Object around(ProceedingJoinPoint pjp) throws Throwable {

System.out.println("这是环绕通知之前的部分!!");

Object proceed = pjp.proceed();//调用目标方法

System.out.println("这是环绕通知之后的部分!!");

return proceed;

}

//异常通知:如果出现异常,就会调用

public void afterException(){

System.err.println("出事啦!出现异常了!!");

}

//后置通知

public void after(){

System.out.println("这是后置通知(出现异常也会调用)!!");

}

}

目标类和测试类省略

猜你喜欢

转载自blog.csdn.net/u011266694/article/details/78918485