I have a Spring app which launches a REST Service within an embedded instance of Jetty, which itself is launched from Spring.
The initial Spring context has an integration and database layer, and launches the Jetty instance. Jetty then calls its own application context file which exposes the REST service.
I would like to know if there’s some way of exposing the initial Spring context to the web context run from within Jetty. Unfortunately I can’t deploy a full J2EE server, and I’m hesitant to run everything from the Web context, relying on Jetty to manage threading and such.
So I found yet a better answer based off the one from ericacm above. The only reason that it’s better is that you can still use
<load-on-startup>for the servlets in the web.xml file.When embedding the Jetty server, you need to create a
WebAppContext. The super-classContextHandlerlets you set an array ofEventListenerwhich includesServletContextListener.So the solution is extend
ContextLoaderand implement both Spring’sApplicationContextAwareand theServletContextListenerinterface. The loader lets you return the parent context set by the contextaware interface, and the listener provides you theServletContextviacontextInitialized().You can then initialize this before any of the Jetty components, and get access to the fully populated
ServletContextas the Jetty server is loading, which gets called before any of the web app’s themselves are initialized.Listener implementation:
Jetty config for WebAppContext (eventually referenced by the server):