为什么一个Annotation Intercepter工作而另一个被忽略?

时间:2016-03-23 17:49:41

标签: java annotations interceptor spring-aop

我为方法级别拦截创建了一个注释。 该类只记录有关应用程序调用日志的统计信息。

然而,它似乎只在某些时候起作用。

获取拦截:

    @LogStats
    public void inboundSms(InboundSms request) {
        <<< do work >>>
        <<< calls sendOutBoundMessage >>>
        <<< do work >>>
    }

没有被拦截:

    @Override
    @LogStats(parameterSeperator=", ", printParamNames=true)
    public SendOutboundResponseType sendOutBoundMessage(String message, String mobileNumber) throws SendOutboundRequestFault {
        <<< do work >>>

        return response;
    }

没有被拦截:

    @POST
    @Consumes(MediaType.APPLICATION_XML)
    @Produces(MediaType.TEXT_PLAIN)
    @LogStats
    public Response inboundSms(InboundSms request) {
        logger.info("inboundSms() invloked on text: " + request.getText());
        try {
            smsService.inboundSms(request);
        } catch(BadRequestException e) {
            return Response.status(Status.BAD_REQUEST).build();
        } catch(Exception e){
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
        return Response.status(Status.OK).build();
    }

上下文文件:

    <!-- AOP Log File Logging -->
    <bean id="statLogger" class="gov.usps.pts.api.statistics.StatLoggingIntercepter">
        <property name="executor" ref="taskExecutor"/>
        <property name="configValueCache" ref="ptsCache" />
    </bean>
    <aop:config>
        <aop:aspect ref="statLogger">
            <aop:pointcut id="statLogSource" expression="@annotation(gov.usps.pts.api.statistics.LogStats)" />
            <aop:around pointcut-ref="statLogSource" method="printStats" />
        </aop:aspect>
    </aop:config>

注释类:

@Target({METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface LogStats {
    boolean printParamNames() default false;
    String parameterSeperator() default MULTI_LINE_SPACER;
    String resultName() default "result";
}

拦截逻辑:

    public Object printStats(ProceedingJoinPoint pjp) throws Throwable {
        boolean methodRan = false;
        Object result = null;

        if (pjp.getSignature() instanceof MethodSignature) {
            MethodSignature signature = (MethodSignature)pjp.getSignature();
            LogStats statConfig = signature.getMethod().getAnnotation(LogStats.class);


            String methodName = signature.getName();
            methodRan = true;
            long start = System.currentTimeMillis();
            try {
                result = pjp.proceed();
                System.out.println(result);
            } finally {
                quietlyLogPerfStats(methodName, signature, statConfig, pjp.getArgs(), start);
            }
        }

        if (!methodRan) {
            result = pjp.proceed();
        }

        return result;
    }

0 个答案:

没有答案