现在的位置: 首页 > 综合 > 正文

Spring 学习之通知

2013年02月05日 ⁄ 综合 ⁄ 共 1905字 ⁄ 字号 评论关闭

   前置通知:    

        在目标方法被调用之前,进行的操作,如:安全检查 或者如下的,向目标方法打个招呼  等等

        public interface MethodBeforeAdvice{

          void before (Method method, Object[] args, Object target) throws Throwable; // 类似动态代理中的方法

        }

 

        public class WelcomeAdvice implements MethodBeforeAdvice{

            public void before(Method method, Object[] args, Object target){

                 Customer customer =  (Customer) args[0];

                 System.out.println("Hello " + customer.getName());

             }

         }

 

         方法结束后,没有任何返回值,因为在执行完这方法后,目标方法将被调用,而应该返回目标方法的值。

         当然也可以制止目标方法被调用,那就是抛出异常或者调用 System.exit();

   

        后置通知:

           在目标方法调用后,再调用此通知

          public interface AfterReturningAdvice{

               void  afterReturning(Object returnValue, Method method,Object[] args, Object target) throws Throwable

           }

 

          public class ThankAdvice  implements AfterReturningAdvice{

              public void afterReturning(Object returnValue, Method method, Object[] arg2, Object target) throws Throwable{

           System.out.println("3Q!");

        } 

          }

     后置通知,虽然可以获得目标方法的返回值,但不能改变他的返回值,要是想不让目标方法正常返回值的话,可以和前置通知一样进行操作。

 

    环绕通知:

      MethodInterceptor 提供了在一个通知对象中实现二种通知的能力:

         public interface MethodInterceptor extends Interceptor{

            Object  invoke(MethodInvocation invocation)

        }

    MethodInterceptor  与前置和后置通知的区别在于:

         1 MethodInterceptor  能够控制目标方法是否真的被调用。MethodInvocation.proceed()

         2 MethodInterceptor  可以让你控制对象的返回值

     public class OnePerCustomerInterceptor implements  MethodInterceptor{

          private Set customers = new HashSet();

          public Object invoke(MethodInvocation invocation) throws Throwable{

               Customer  customer = (Customer)  invocation.getArgyments()[0]; // 获得当前用户

               if(customers .contain(customer )){

                  throw new java.runException();

               }

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

               customers.add(customer );   // 添加用户

               return  squishee;  // 返回目标对象

          }

     }

抱歉!评论已关闭.