【问题标题】:Nested annotations method interception in GuiceGuice中的嵌套注释方法拦截
【发布时间】:2016-03-27 17:45:17
【问题描述】:

我搜索了很多,但找不到任何有用的东西。

问题: 我创建了自定义注释,例如:

@MapExceptions(value = {
        @MapException(sources = {IllegalArgumentException.class, RuntimeException.class}, destination = BadRequestException.class),
        @MapException(sources = {RuntimeException.class}, destination = BadRequestException.class)
})

我正在使用 Guice 进行 DI。

  1. 我必须编写两个方法拦截器吗?实际工作正在 @MapException 中完成
  2. 如果是,那么如何从@MapExceptions 拦截器调用方法调用@MapException 拦截器调用方法?我不想重复代码。
  3. 我的@MapException 拦截器如下所示

公共类 MapExceptionInterceptor 实现 MethodInterceptor {

@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    try {
        return invocation.proceed();
    } catch (Exception actualException) {
        Method method = invocation.getMethod();
        Annotation[] annotations = method.getDeclaredAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation instanceof MapException) {
                MapException mapException = (MapException) annotation;
                Class<? extends Throwable> destinationClass = mapException.destination();
                Class<? extends Throwable>[] sourceClasses = mapException.sources();
                for (Class sourceExceptionClass : sourceClasses) {
                    if (actualException.getClass().isInstance(sourceExceptionClass)) {
                        Constructor ctr = destinationClass.getConstructor(String.class);
                        throw (Throwable) ctr.newInstance(actualException.getMessage());
                    }
                }
            }
        }
        throw actualException;
    }
}

}

我目前正在使用以下绑定

bindInterceptor(Matchers.any(), Matchers.annotatedWith(MapException.class), new MapExceptionInterceptor());

这样好吗?或者我可以改进?

谢谢!

【问题讨论】:

    标签: java guice interceptor


    【解决方案1】:

    所以,内部注解只是一个数据包。 为了解决这个问题,我为外部注释 (MapExceptions) 编写了拦截器,它完成了所有工作。

    【讨论】:

    • 你能提供你用来解决这个问题的代码吗?
    猜你喜欢
    • 2015-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-20
    • 2012-02-01
    • 2012-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多