Apache Tomcat:“上下文变量”
我是 Tomcat 的新手,因此有几个问题。我希望从任何代码中都可以获取某些可用于我的上下文的对象。我能够通过 DataSource 实现此目的,因为这是 Tomcat 指南中使用的示例。
我想添加 2 个额外的对象: 在构造函数中使用此数据源的对象 A 对象 B 在其构造函数中使用对象 A
我该怎么做?
I'm new to Tomcat and hence have a few question. I want to have certain objects available for my Context from any code. I was able to achieve this for a DataSource because that is the example used in the Tomcat guide.
I would like to add 2 additional objects:
Object A that uses this DataSource in the Constructor
Object B that uses Object A in it's constructor
How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的方法可能是使用 ContextListener 将对象 A 和 B 插入到上下文中。请参阅 http://download.oracle.com/javaee/1.4/tutorial/ doc/Servlets4.html 中的使用示例:在
contextInitialized
方法中,您可以从上下文中获取数据源,创建对象 A 和 B,然后将它们存储回上下文中。What's probably the easiest thing to do is use a
ContextListener
that inserts Objects A and B into the Context. See http://download.oracle.com/javaee/1.4/tutorial/doc/Servlets4.html for a usage example: in thecontextInitialized
method you can grab the datasource out of the context, create objects A and B and then store them back into the context.根据 Tomcat 5.5 规范。发现于 http://tomcat.apache.org/tomcat-5.5-doc /config/globalresources.html 我发现
Context
无法执行此类技巧,也不适合此类用途。您希望从“任何代码”中获得一些对象。如果这仅限于单个 Web 应用程序,那么您可以考虑 @Fermi 的答案,或者也许您应该启动 Spring
ApplicationContext
。如果您还不熟悉 Spring 框架,这可能听起来有点太困难,但是如果您继续开发应用程序,我认为如果 Spring 上下文从一开始就已经存在,那么到了某个时候,事情就会变得更容易。 (如果您选择这种方式,如果您需要设置 Spring 的帮助,请在评论中告诉我。)According to the Tomcat 5.5 spec. found on http://tomcat.apache.org/tomcat-5.5-doc/config/globalresources.html I see that
Context
is not capable of doing such tricks and is not for such usages.You'd like to have some objects available from "any code". If this any is confined to a single web application, than you can consider @Fermi's answer or maybe you should launch a Spring
ApplicationContext
. That might sound a bit too difficult if you're not familiar with Spring Framework yet, however if you keep developing your application I think there will be a certain point where things start to become easier if a Spring context already exists from the beginning. (Tell me in a comment if you need help with setting up Spring provided you choose that way.)