【问题标题】:Jersey and AOP without Spring没有 Spring 的 Jersey 和 AOP
【发布时间】:2013-08-23 04:13:23
【问题描述】:

我在 Jersey 2.1 中使用 Grizzly。 我想为记录目的添加一个方面(在每个方法执行之前和之后)。 不使用 Spring 或 Google-Guice 是否可以做到这一点?

谢谢

【问题讨论】:

  • 您可以使用 AspectJ,但这可能比与 Spring 或 Guice 集成更复杂,因为它是自己的语言。

标签: java logging jersey aop


【解决方案1】:

您可以使用 Jersey 提供的 monitoring 功能(特别是通过 event listeners)实现非常相似的功能。基本上,您需要创建和注册ApplicationEventListenerRequestEventListener 的实例,您将在其中收听RESOURCE_METHOD_STARTRESOURCE_METHOD_FINISHED 事件。

@Provider
public class MyApplicationEventListener implements ApplicationEventListener {

    @Override
    public void onEvent(ApplicationEvent event) {
        // NOOP.
    }

    @Override
    public RequestEventListener onRequest(RequestEvent requestEvent) {
        return new RequestEventListener() {

            @Override
            public void onEvent(final RequestEvent event) {
                switch (event.getType()) {
                    case RESOURCE_METHOD_START:
                        logMethod(event.getUriInfo(), true);
                        break;

                    case RESOURCE_METHOD_FINISHED:
                        logMethod(event.getUriInfo(), false);
                        break;
                }
            }

            private void logMethod(final ExtendedUriInfo uriInfo, final boolean entering) {
                final Class<?> resource = uriInfo
                        .getMatchedResources().get(0).getClass();

                final Method method = uriInfo
                        .getMatchedResourceMethod()
                        .getInvocable()
                        .getHandlingMethod();

                if (entering) {
                    logger.entering(resource.toString(), method.toString());
                } else {
                    logger.exiting(resource.toString(), method.toString());
                }
            }
        };
    }
}

将监听器注册到您的应用程序中:

public class MyApplication extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        final HashSet<Class<?>> classes = new HashSet<Class<?>>();

        // Add root resources.
        classes.add(HelloWorldResource.class);
        
        // Add ApplicationEventListener.
        classes.add(MyApplicationEventListener.class);
        
        return classes;
    }
}

注意:这些事件仅围绕“待执行”资源方法触发,而不针对可能在资源匹配阶段执行的子资源定位器。


编辑 1

要记录每个调用的方法(甚至是从 JAX-RS 资源方法调用的方法),请参阅 AspectJ 项目。

【讨论】:

  • 好的,它可以工作,但我怎样才能为资源调用的方法获得相同的结果?我还想记录资源方法调用的方法的输入/输出参数。
  • 为此,您需要使用 AspectJ 或类似的库(请参阅EDIT 1)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-04
  • 2011-08-23
相关资源
最近更新 更多