I'm new to Tomcat and hence have a few quest开发者_开发技巧ion. 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?
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 the contextInitialized
method you can grab the datasource out of the context, create objects A and B and then store them back into the context.
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.)
精彩评论