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();
1
  • Could you post the web.xml that you are using (if indeed you are using one)? Commented Apr 16, 2014 at 11:44

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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)
Could you link me to one of the tutorials please?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.