有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java启动和停止JMSContext

{}有两种简便的方法:

@Inject
JMSContext jmsContext;

this.jmsContext.start();
this.jmsContext.stop();

但是,我不允许使用这些方法,因为start()的JavaDoc声明“如果JMSContext是容器管理(注入)的,则不得使用此方法。这样做将导致引发非法StateRuntimeException。”

(我试过了,这两种方法都会引发异常。)

那么,如果JMSContext是容器管理的,我该如何启动和停止它呢


共 (1) 个答案

  1. # 1 楼答案

    容器管理的JMSContext的生命周期(start()stop())由容器管理。这意味着注入的JMSContext在注入时已经启动,并且将由容器停止,具体取决于使用JMSContext的上下文

    以下是JMS Specification 2.0Download)对这个话题的看法:

    12.4.4. Scope of injected JMSContext objects

    • If an injected JMSContext is used in a JTA transaction (both bean-managed and container-managed), its scope will be that of the transaction. This means that:
      • The JMSContext object will be automatically created the first time it is used within the transaction.
      • The JMSContext object will be automatically closed when the transaction is committed.
      • If, within the same JTA transaction, different beans, or different methods within the same bean, use an injected JMSContext which is injected using identical annotations then they will all share the same JMSContext object.
    • If an injected JMSContext is used when there is no JTA transaction then its scope will be the existing CDI scope @RequestScoped. This means that:
      • The JMSContext object will be created the first time it is used within a request.
      • The JMSContext object will be closed when the request ends.
      • If, within the same request, different beans, or different methods within the same bean, use an injected JMSContext which is injected using identical annotations then they will all share the same JMSContext object.
    • If injected JMSContext is used both in a JTA transaction and outside a JTA transaction then separate JMSContext objects will be used, with a separate JMSContext object being used for each JTA transaction as described above.

    它进一步描述了对JMSContextAPI的限制:

    12.4.5. Restrictions on use of injected JMSContext objects

    However, to avoid the possibility of code in one bean having an unexpected effect on a different bean, the following methods which change the public state of a JMSContext will not be permitted if the JMSContext is injected.

    • setClientID
    • setExceptionListener
    • stop
    • acknowledge
    • commit
    • rollback
    • recover
    • setAutoStart
    • start
    • close

    [...]

    These restrictions do not apply when the JMSContext is managed by the application.