Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: Make ServeltDispatcher Context await until another Context finish loading

I would like to load DBbuildServletDispatcher, after finishing Context loading, eg on ApplicationListener<ContextRefreshedEvent> event fire message to build(or proceed building) AppServletDispatcher Context

SpringMultiDisp

In other words could AppDispatcher Context wait until finishing creation of DBbuild Context? Are there any common ways of doing this?

like image 975
Rudziankoŭ Avatar asked Jun 22 '17 10:06

Rudziankoŭ


2 Answers

It is simple. Remember the param scope is of two types - context param and servlet's init param. What you need is all dependencies must be initialised before the child context is loaded. Here DBbuildServletDispatcher should be initialised in the parent context, that is ApplicationContext, and AppServletDispatcher is WebApplicationContext which is the child context of the application context

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/spring/DBbuildServletDispatcher.xml
    </param-value>
</context-param>



<servlet>
    <servlet-name>firstServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/AppServletDispatcher.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>my-servlet</servlet-name>
    <url-pattern>/abc/* </url-pattern>
</servlet-mapping>

The first part with context param loads the context file and create the ApplicationContext. The second part defines the WebApplicationContext. Refer here and WebApplicationContextUtils may also be utilized.

like image 195
hi.nitish Avatar answered Nov 11 '22 07:11

hi.nitish


Something like this may work. You load only the DBbuildContext.xml (applicationContext.xml)

after adding this line:

<bean id="eventListenerBean" class="a.b.c.ApplicationListenerBean" />

Then, define a class

package a.b.c;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

public class ApplicationListenerBean implements ApplicationListener {

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ContextRefreshedEvent) {
            ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("appServletContext.xml");

        }
    }
}

Now the appServletContext.xml will only create a context when the dbBuildContext.xml has loaded.

like image 39
mikep Avatar answered Nov 11 '22 07:11

mikep