第一步:配置实现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 }
1 <bean id="outsideInvokeLogAdvice" class="com.ali.luna.commons.service.interceptor.OutsideInvokeLogInterceptor" />
配置切点:
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>
配置自动代理:
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>
时间: 2024-10-10 05:57:37