0

I have my main Spring context which is created when my application is started. Within this context is the database connection and the embedded web server.

The embedded webserver is then started with a DispatcherServlet with its own Spring Context.

From one of the DispatcherServlets, I wish to access the database, but because the connection is not in its context, I can't.

What is the Java/Spring way to solve this problem?

This is my web.xml:

<servlet>
    <servlet-name>App</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:/jettycontext.xml</param-value>
    </init-param>
</servlet>

This is the entrypoint main method:

try (ConfigurableApplicationContext context = new GenericXmlApplicationContext("maincontext.xml")) {

    JServer server = context.getBean(JServer.class);
    server.start();
}

This is the JServer.start() method:

server = new Server(8080);        
server.setHandler(new WebAppContext("./webapp", "/"));
server.start();
server.join();
Cheetah
  • 13,785
  • 31
  • 106
  • 190

1 Answers1

0

Try adding

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:maincontext.xml</param-value> <!-- or wherever else you have the maincontext.xml file-->
</context-param>

<listener>
   <listener-class>
      org.springframework.web.context.ContextLoaderListener
   </listener-class>
</listener>

to web.xml

See this, this, and this tutorial.

This, this and this SO question describe the difference between the two contexts

Community
  • 1
  • 1
geoand
  • 60,071
  • 24
  • 172
  • 190
  • Erm, I am new to Java but I am 99.99% sure this isn't what I want. Won't this just load the maincontext again but within the servlet. – Cheetah Apr 16 '14 at 11:55
  • It should cause the main context to be the parent of web context (which you are now loading in Dispatcher Servlet), thus giving the beans of the web context access to the beans of the root context. It's a fairly standard setup that you encounter in multiple tutorials (and which I have you many times myself) – geoand Apr 16 '14 at 12:05
  • Could you link me to one of the tutorials please? – Cheetah Apr 16 '14 at 16:45