首页 > 解决方案 > How can I disable Java EE interceptor on application start up, for example by condition from database logger=info?

问题描述

I use Java EE and WebLogic server. I declare interceptor with annotated style: @Interceptor. I need to add some functionality which would disable certain interceptor. I use annotation to mark methods when Interceptor needs to invoke.


@Inherited
@InterceptorBinding
@Retention(RUNTIME)
@Target({METHOD, TYPE})
public @interface Traced {
}

 @Traced
    @Interceptor
    @Priority(Interceptor.Priority.APPLICATION)
    public class MethodInvocationInterceptor implements Serializable {

        private static final Logger LOG = Logger.getLogger(MethodInvocationInterceptor.class);

        @AroundInvoke
        public Object intercept(final InvocationContext ctx) throws Exception {
          LOG.trace(ctx.getMethod().getName() + " method started");
        return ctx.proceed();
      }

标签: javajakarta-eeweblogiccdiinterceptor

解决方案


我能想到三种合理的方法。

首先与@Nikos 建议的相同,始终启用拦截器并根据配置添加条件逻辑。

第二种方法需要您监视AfterTypeDiscoveryevent的 CDI 扩展。这使您可以获取备选方案、拦截器和装饰器的列表。这些列表是可变的,一旦您更改它们,容器必须考虑更改值。移除拦截器应该会导致拦截器被禁用。

这种方法再次使用 CDI 扩展,要求您使用事件监视AnnotatedType拦截器ProcessAnnotatedType并使用方法禁用它veto()。或者,如果否决没有削减它,您可以更改AnnotatedType并删除/替换拦截器绑定(尽管这种方法听起来有点“hacky”,因为您以没有绑定的拦截器结束)。


推荐阅读