• AOP编程实例:拦截器拦截拦截某个实现类的方法


    第一步:配置实现MethodInterceptor的切面

    java代码

     1 public class OutsideInvokeLogInterceptor implements MethodInterceptor{  
     2     private static Logger log = Logger.getLogger("outsideInvoke");  
     3     
     4     @Override  
     5     public Object invoke(MethodInvocation invocation) throws Throwable {  
     6         String methodName = invocation.getMethod().toString();  
     7         Object returnValue = invocation.proceed();  
     8         if (returnValue == null) {  
     9             log.warn("调用 " + methodName + "is fail,返回的result结果为空,方法入参为:(" + parseArguments(invocation.getArguments()) + ")");  
    10             return ResultDTO.getFailureResult(BSErrorCode.INTERNAL_ERROR, BaseKeyMsgCode.RETURN_RESULTDTO_IS_NULL);  
    11         }else{  
    12             if(returnValue instanceof ResultDTO){  
    13                 ResultDTO<Object> resultDTO = (ResultDTO<Object>)returnValue;  
    14                 if(!resultDTO.isSuccess()){  
    15                     log.warn("调用 " + methodName + " is fail ,方法入参为:(" + parseArguments(invocation.getArguments()) + ")"  
    16                          + "返回值:" +resultDTO.getCode() + "," + resultDTO.getKey());  
    17                 } else{  
    18                     log.info("调用 " + methodName + " is success ,方法入参为:(" + parseArguments(invocation.getArguments()) + ")");  
    19                 }  
    20             }  
    21         }  
    22         return returnValue;  
    23   
    24     }  
    25 }  
    View Code
    1 <bean id="outsideInvokeLogAdvice" class="com.ali.luna.commons.service.interceptor.OutsideInvokeLogInterceptor" /> 
    View Code

    配置切点:

    1 <bean id="methodPointcut" class="org.springframework.aop.support.NameMatchMethodPointcut">  
    2         <property name="mappedNames">  
    3             <list>  
    4                 <value>add*</value>  
    5             </list>  
    6         </property>  
    7     </bean>  
    View Code

    配置自动代理:

     1 <bean id="outsideInvokeLogInterceptor" class="org.springframework.aop.support.DefaultPointcutAdvisor">  
     2     <property name="pointcut" ref="methodPointcut"/>  
     3     <property name="advice" ref="outsideInvokeLogAdvice"/>  
     4 </bean>  
     5 <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">  
     6     <property name="beanNames">  
     7         <list><value>activityService</value></list>  
     8     </property>  
     9     <property name="interceptorNames">  
    10         <list>  
    11             <value>outsideInvokeLogInterceptor</value>  
    12         </list>  
    13     </property>  
    14 </bean>  
    View Code
  • 相关阅读:
    [悟]你为什么想创业
    [悟] 因上努力,果上随缘
    自己写个多任务多线程断点下载框架
    大道甚夷,而人好径
    [经验帖]外包如何定价
    python 基础语法
    python 中文编码问题
    python的运行机制和版本区别
    [转]linux 调用动态库so文件
    shell join详解
  • 原文地址:https://www.cnblogs.com/dobestself-994395/p/4272835.html
Copyright © 2020-2023  润新知