spring学习笔记(五)

1、后置通知

    需求:调用相应业务方法后,完成资源的关闭。

   a、 在beans.xml中配置

 1 ....
 2 
 3 <beans>
 4 
 5   <!--配置被代理对象-->
 6   <bean id="test1Service" class="com.huawei.aop.Test1Service">
 7       <property name="name" value="spring"/>
 8   </bean>
 9 
10   <!--配置后置通知-->
11   <bean id="myAfterServiceAdvice" class="com.huawei.aop.MyAfterServiceAdvice"/>
12 
13   <!--配置代理对象-->
14   <bean id="proxyFactoryBean" class="org.springframework.aop.framework.ProxyFactoryBean">
15 
16   <!--配置代理接口集-->
17      <property name="proxyInterfaces">
18         <list>
19            <value>com.huawei.aop.Test1ServiceInter</value>
20            <value>com.huawei.aop.Test2ServiceInter</value>   
21         </list>
22       </property >
23 
24       <!--将通知织入代理-->
25       <property name="interceptorNames">
26           <list>
27                <value>myAfterServiceAdvice</value>
28           </list>
29       </property>
30   
31       <!--配置被代理对象-->
32       <property rel="target" name="test1Service"/>
33     </bean>
34 </beans>


   b、实现 AfterReturningAdvice 接口

 1 package com.huawei.aop;
 2 
 3 import java.lang.reflect.Method;
 4 
 5 import org.springframework.aop.AfterReturningAdvice;
 6 
 7 public class MyAfterServiceAdvice implements AfterReturningAdvice
 8  {
 9 
10     @Override
11     public void afterReturning(Object arg0, Method arg1, Object[] arg2,
12             Object arg3) throws Throwable 
13        {
14 
15         System.out.println("关闭资源");
16     }
17 
18 }

   3.测试类

 1 package com.huawei.aop;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 public class AopTest {
 7 
 8     /**
 9      *  aop 编程测试类
10      */
11     public static void main(String[] args)
12     {
13         //获取应用上下文对象
14         ApplicationContext ac = new ClassPathXmlApplicationContext("com/huawei/aop/beans.xml");
15         
16         //获取实例对象
17         Test1ServiceInter ti = (Test1ServiceInter) ac.getBean("proxyFactoryBean");
18         
19         //调用实例方法
20         ti.sayHello();
21         
22         ((Test2ServiceInter) ti).sayBye();
23     }
24 
25 }
原文地址:https://www.cnblogs.com/yiliweichinasoft/p/3567690.html