【问题标题】:Context not active exception while injecting request scope bean in application scope class with Postconstruct method使用 Postconstruct 方法在应用程序范围类中注入请求范围 bean 时上下文不活动异常
【发布时间】:2020-11-01 01:07:24
【问题描述】:

当我尝试在应用程序范围 bean 中注入请求范围 bean 时,出现以下错误。

Method threw 'org.jboss.weld.contexts.ContextNotActiveException' exception. Cannot evaluate com.example.flow.txn.TxnMessageProcessor$Proxy$_$$_WeldClientProxy.toString()

代码参考:

@ApplicationScoped
public class TxnMessageObserver {

    private static final Logger logger = LoggerFactory.getLogger(TxnMessageObserver.class);

    @Inject
    private TxnMessageProcessor processor;
//message is observed here

  public void postConstruct(@Observes @Initialized(ApplicationScoped.class) Object o) {
        logger.info("Subscribing to queue [{}] for msg.", queue);
        consumer.subscribe(queue);
    }



}


@RequestScoped
public class TxnMessageProcessor {

    private static final Logger logger = LoggerFactory.getLogger(TxnMessageProcessor.class);
//all processing happens here

}

我需要处理请求范围内的每条消息。

【问题讨论】:

标签: java jboss cdi java-ee-8


【解决方案1】:

我不知道问题的确切原因是什么。但我可以确认您可以将@ReqeustScoped bean 注入@ApplicationScoped。我在许多包含数百个类的应用程序中都这样做了,而且它开箱即用。

【讨论】:

    【解决方案2】:

    如果在初始化 servlet 上下文时急切地构造 applicationscoped bean(就像这里的情况),则没有请求上下文,因此没有 requestscoped bean。

    由于完全不清楚您要实现的目标(您的代码不是minimal reproducible example,让我指点一下

    (全部通过this search找到)

    因此,注入 requestscoped bean 是危险的,我强烈建议在特定方法中检索所需的 requestscoped bean,或者反过来,将 applicationscoped bean 注入 requestscoped 中,并在其上调用方法,传入自身.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-13
      • 1970-01-01
      • 2013-08-26
      • 1970-01-01
      • 1970-01-01
      • 2015-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多