JavaBlog.fr / Java.lu DEVELOPMENT,Java,Spring Spring: access to Spring context in all places or layers of an application

Spring: access to Spring context in all places or layers of an application

Hi,

After my last post concerning the customization of the Spring Context ‘XmlWebApplicationContext’, I will present you a simple solution to access to Spring context in all places of an application.
For example, in a Spring MVC application with ORM layer, commonly, we have the following stack:

SpringWebMVCCtrler
     ==calls==> ServiceDelegate
            ==calls==> ServiceImpl
                   ==calls==> HibernateDaoImpl

..so, it is necessary to have access to the context in all places or layers of an application.

First, we will create a classic servlet context listener SpringContextLoader which implements ServletContextListener. During the initialization context, this listener will get a parameter ‘CONFIG_SPRING_FILE’ configured in web.xml, and it will call a singleton named ApplicationContextContainer use this parameter.

public class SpringContextLoader implements ServletContextListener {

	// -------------------------------------------------------------- CONSTANTS
	// ----------------------------------------------------- PRIVATE ATTRIBUTES
	// ------------------------------------------------------------- EXCEPTIONS
	// ------------------------------------------------------- INTERNAL CLASSES
	// ----------------------------------------------------------- CONSTRUCTORS
	// --------------------------------------------------------- PUBLIC METHODS
	
	/**
	 * Method contextDestroyed
	 * @param arg0
	 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
	 */
	public void contextDestroyed(ServletContextEvent arg0) {
	}

	/**
	 * Method contextInitialized
	 * @param arg0
	 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
	 */
	public void contextInitialized(ServletContextEvent ctx) {
		String springFileName = ctx.getServletContext().getInitParameter("CONFIG_SPRING_FILE");
		ApplicationContextContainer.getInstance(springFileName, ctx.getServletContext());
	}

	// -------------------------------------------------------- PRIVATE METHODS
	// ------------------------------------------------------ PROTECTED METHODS
	// --------------------------------------------- ADVANCED GETTERS & SETTERS
	// ------------------------------------------------------ GETTERS & SETTERS
}

Then, we will create the singleton ApplicationContextContainer which gives an access to a container containing the Spring context with the XmlWebApplicationContext type.
Once, the context loaded, the next calls to the ‘getInstance()’ or ‘getInstance(String springContextFile, ServletContext servletContext)’ will return the same instance of context.

public class ApplicationContextContainer {
	
    // ------------------------------------------------------------------ LOG4J
    private static Log log = LogFactory.getLog(ApplicationContextContainer.class);

    // -------------------------------------------------------------- CONSTANTS
    // Default Spring context file
    private final static String SPRING_BUSINESS_CONFIG_XML = "/WEB-INF/spring-root-applicationContext-cfg.xml";
    

    // ----------------------------------------------------- PRIVATE ATTRIBUTES
    /**
     * Instance
     */
    private static ApplicationContextContainer instance = null;
    
    /**
     * Contains the spring configuration.
     */
    private XmlWebApplicationContext ctx = null;

    // ------------------------------------------------------------- EXCEPTIONS
    // ------------------------------------------------------- INTERNAL CLASSES
    // ----------------------------------------------------------- CONSTRUCTORS
    private ApplicationContextContainer() {}
    // --------------------------------------------------------- PUBLIC METHODS
    
    /**
     * Getinstance method.
     */
    public static synchronized ApplicationContextContainer getInstance() {
        return getInstance(SPRING_BUSINESS_CONFIG_XML, null);
    }
    public static synchronized ApplicationContextContainer getInstance(String springContextFile, ServletContext servletContext) {
    	if (null == instance) {
    		instance = new ApplicationContextContainer();
    		instance.ctx = new XmlWebApplicationContext();  
    		instance.ctx.setConfigLocation(springContextFile);
    		instance.ctx.setServletContext(servletContext);
    		instance.ctx.refresh();
        } // end-if
        return instance;
    }
    
    /**
     * Retrieve the spring bean corresponding to the given key.
     * @param key
     * @return
     */
    public static Object getBean(String key) {
        return getInstance().ctx.getBean(key);
    }
    
    public XmlWebApplicationContext getContext() {
        return ctx;
    }
    
    // -------------------------------------------------------- PRIVATE METHODS
    // ------------------------------------------------------ PROTECTED METHODS
    // --------------------------------------------- ADVANCED GETTERS & SETTERS
    // ------------------------------------------------------ GETTERS & SETTERS
}

More, we need a enumeration or a class containing the names of beans configured in the Spring Context:

public class DataConstHelper {
	public static final String USER_DAO_HIBERNATE_IMPL = "UserDaoHibernateImpl";
	public static final String BOOK_DAO_HIBERNATE_IMPL = "BookDaoHibernateImpl";
	public static final String USER_SERVICE_IMPL = "UserServiceImpl";
	public static final String BOOK_SERVICE_IMPL = "BookServiceImpl";
	public static final String USER_VALIDATOR = "userValidator";
}

A more important thing, is the configuration of these beans in the web.xml deployment descriptor (DD) file:

<!-- ################### Root WebApplicationContext ################### -->
<!-- Method n°1 of Spring context loading at startup -->
<!-- ADVANTAGE: This method centralizes the context in a class available in STATIC ways-->
<listener>
	<listener-class>com.ho.persistence.hibernate.spring.ex1.utils.SpringContextLoader</listener-class>
</listener>
<context-param>
	<param-name>CONFIG_SPRING_FILE</param-name>
	<param-value>/WEB-INF/spring-root-applicationContext-cfg.xml</param-value>
</context-param>

A example of Spring context loading at startup ís the following configuration in DD file which we don’t use in our example:

<!-- Method n°2 Spring context loading at startup  -->
<!--
<listener>
	<listener-class>
		org.springframework.web.context.ContextLoaderListener
	</listener-class>
</listener>
<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>WEB-INF/spring-root-applicationContext-cfg.xml</param-value>
</context-param>
-->


1 thought on “Spring: access to Spring context in all places or layers of an application”

  1. Hi,

    It took two days to find a decent working example like this.Thank you 🙂

    Thanks and Regards
    Kavya M

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

Related Post