Announcement Announcement Module
Collapse
No announcement yet.
Access ApplicationContext loaded by Listener Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Access ApplicationContext loaded by Listener

    Hi,
    Anyone known how to load the applicationContext accessing to Listener?

    The example: I've a listener that load the application context in web.xml

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

    <listener>
    <description>ApplicationContextLoaderListener</description>
    <listener-class>org.springframework.web.context.ContextLoade rListener</listener-class>
    </listener>

    So, what should i do to access to defined beans into applicationcontext by my application?

    I don't want to access it by servlet!

    Any suggest?

  • #2
    Have a look at WebApplicationContextUtils.getWebApplicationContex t(ServletContext sc)

    Comment


    • #3
      If can't or don't want to use the servlet context, you could add a "ProxyContextLoaderListener" to your application:

      Code:
      package demo.spring
      
      import javax.servlet.ServletContextEvent;
      import org.springframework.web.context.ContextLoader;
      import org.springframework.web.context.ContextLoaderListener;
      import org.springframework.web.context.WebApplicationContext;
      
      public class ProxyContextLoaderListener extends ContextLoaderListener {
      	private static WebApplicationContext ctx;
      
      	@Override
      	public void contextInitialized(ServletContextEvent event) {
      		super.contextInitialized(event);
      		ctx = ContextLoader.getCurrentWebApplicationContext();
      	}
      
      	@Override
      	public void contextDestroyed(ServletContextEvent event) {
      		super.contextDestroyed(event);
      		ctx = null;
      	}
      
      	public static WebApplicationContext getCtx() {
      		return ctx;
      	}
      }
      The code that needs to access a bean created by ApplicationContext could be as follows:

      Code:
              ...
              MyClass cl = (MyClass) ProxyContextLoaderListener.getCtx().getBean(
      				"myBeanId");
              ...
      In the web.xml file you specify the ProxyContextLoaderListener instead of the standard Spring ContextLoaderListener:

      Code:
           ...
          <listener>
              <listener-class>
              	demo.spring.ProxyContextLoaderListener
              </listener-class>
          </listener>
          ...

      Comment

      Working...
      X