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.

01public class SpringContextLoader implements ServletContextListener {
02 
03    // -------------------------------------------------------------- CONSTANTS
04    // ----------------------------------------------------- PRIVATE ATTRIBUTES
05    // ------------------------------------------------------------- EXCEPTIONS
06    // ------------------------------------------------------- INTERNAL CLASSES
07    // ----------------------------------------------------------- CONSTRUCTORS
08    // --------------------------------------------------------- PUBLIC METHODS
09     
10    /**
11     * Method contextDestroyed
12     * @param arg0
13     * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
14     */
15    public void contextDestroyed(ServletContextEvent arg0) {
16    }
17 
18    /**
19     * Method contextInitialized
20     * @param arg0
21     * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
22     */
23    public void contextInitialized(ServletContextEvent ctx) {
24        String springFileName = ctx.getServletContext().getInitParameter("CONFIG_SPRING_FILE");
25        ApplicationContextContainer.getInstance(springFileName, ctx.getServletContext());
26    }
27 
28    // -------------------------------------------------------- PRIVATE METHODS
29    // ------------------------------------------------------ PROTECTED METHODS
30    // --------------------------------------------- ADVANCED GETTERS & SETTERS
31    // ------------------------------------------------------ GETTERS & SETTERS
32}

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.

01public class ApplicationContextContainer {
02     
03    // ------------------------------------------------------------------ LOG4J
04    private static Log log = LogFactory.getLog(ApplicationContextContainer.class);
05 
06    // -------------------------------------------------------------- CONSTANTS
07    // Default Spring context file
08    private final static String SPRING_BUSINESS_CONFIG_XML = "/WEB-INF/spring-root-applicationContext-cfg.xml";
09     
10 
11    // ----------------------------------------------------- PRIVATE ATTRIBUTES
12    /**
13     * Instance
14     */
15    private static ApplicationContextContainer instance = null;
16     
17    /**
18     * Contains the spring configuration.
19     */
20    private XmlWebApplicationContext ctx = null;
21 
22    // ------------------------------------------------------------- EXCEPTIONS
23    // ------------------------------------------------------- INTERNAL CLASSES
24    // ----------------------------------------------------------- CONSTRUCTORS
25    private ApplicationContextContainer() {}
26    // --------------------------------------------------------- PUBLIC METHODS
27     
28    /**
29     * Getinstance method.
30     */
31    public static synchronized ApplicationContextContainer getInstance() {
32        return getInstance(SPRING_BUSINESS_CONFIG_XML, null);
33    }
34    public static synchronized ApplicationContextContainer getInstance(String springContextFile, ServletContext servletContext) {
35        if (null == instance) {
36            instance = new ApplicationContextContainer();
37            instance.ctx = new XmlWebApplicationContext(); 
38            instance.ctx.setConfigLocation(springContextFile);
39            instance.ctx.setServletContext(servletContext);
40            instance.ctx.refresh();
41        } // end-if
42        return instance;
43    }
44     
45    /**
46     * Retrieve the spring bean corresponding to the given key.
47     * @param key
48     * @return
49     */
50    public static Object getBean(String key) {
51        return getInstance().ctx.getBean(key);
52    }
53     
54    public XmlWebApplicationContext getContext() {
55        return ctx;
56    }
57     
58    // -------------------------------------------------------- PRIVATE METHODS
59    // ------------------------------------------------------ PROTECTED METHODS
60    // --------------------------------------------- ADVANCED GETTERS & SETTERS
61    // ------------------------------------------------------ GETTERS & SETTERS
62}

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

1public class DataConstHelper {
2    public static final String USER_DAO_HIBERNATE_IMPL = "UserDaoHibernateImpl";
3    public static final String BOOK_DAO_HIBERNATE_IMPL = "BookDaoHibernateImpl";
4    public static final String USER_SERVICE_IMPL = "UserServiceImpl";
5    public static final String BOOK_SERVICE_IMPL = "BookServiceImpl";
6    public static final String USER_VALIDATOR = "userValidator";
7}

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

01<!-- ################### Root WebApplicationContext ################### -->
02<!-- Method n°1 of Spring context loading at startup -->
03<!-- ADVANTAGE: This method centralizes the context in a class available in STATIC ways-->
04<listener>
05    <listener-class>com.ho.persistence.hibernate.spring.ex1.utils.SpringContextLoader</listener-class>
06</listener>
07<context-param>
08    <param-name>CONFIG_SPRING_FILE</param-name>
09    <param-value>/WEB-INF/spring-root-applicationContext-cfg.xml</param-value>
10</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:

01<!-- Method n°2 Spring context loading at startup  -->
02<!--
03<listener>
04    <listener-class>
05        org.springframework.web.context.ContextLoaderListener
06    </listener-class>
07</listener>
08<context-param>
09    <param-name>contextConfigLocation</param-name>
10    <param-value>WEB-INF/spring-root-applicationContext-cfg.xml</param-value>
11</context-param>
12-->


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