【发布时间】:2017-06-22 15:35:54
【问题描述】:
假设我有一个部署到 TomEE (Plume 7.0.2) 的 Web 应用程序。对于这个应用程序,我想创建一个负责通过 JMS 发送消息的中心类。我的第一个想法是创建一个没有映射的 servlet,它会注入所需的字段:
public class JMSSendingServlet extends HttpServlet {
@Resource(mappedName = "jms/logging")
private Queue loggingQueue;
@Resource
private ConnectionFactory connectionFactory;
public void sendMessage(String text) throws JMSException {
Connection connection = connectionFactory.createConnection();
//and so on...
producer.send(message);
}
}
但是,为了从应用程序的其余部分访问此方法,我需要将方法和字段设为静态,或者以某种方式获取该 servlet 的实例。由于我不能(或不应该)对静态字段执行依赖注入,我正在尝试为第二个选项找到解决方案。这是我的尝试:
public class JMSSendingServlet extends HttpServlet {
private static JMSSendingServlet instance;
//...
@Override
public void init(ServletConfig config) throws ServletException {
instance = this;
super.init(config);
}
public static JMSSendingServlet getInstance() {
return instance;
}
}
//usage:
public class SomeClass {
public void someMethod() {
JMSSendingServlet.getInstance().sendMessage("Hello");
}
}
因为我没有这个 servlet 的任何映射并且它通过<load-on-startup/> 加载它,所以应该只存在它的一个实例。但是我仍然对这种解决方案感到有些不舒服。在我看来它很脏,至少因为 getInstance 可以返回 null。
放弃依赖注入并使用 JNDI 获取ConnectionFactory 和Queue 会更干净(如果可能的话)吗?还有其他更好的解决方案吗?
【问题讨论】:
-
您使用的是什么版本的 TomEE?
-
@SteveC 最新稳定的 Plume 7.0.2
标签: jakarta-ee jms jndi apache-tomee tomee-7