How to get Spring App Context in Spring

Jin
2004-08-06
2004-08-06
  • Jin

    Jin - 2004-08-06

    Hi,

    I was playing Spring framework for couple days and got confused about the application context access.

    To my understanding, in order to get a bean, you should get the application context and call getBean. In the servlet layer it is easy, all you need to do is

    // test the spring framework
    ServletContext servletContext =this.getServletContext();

    WebApplicationContext wac = WebApplicationContextUtils.
    getRequiredWebApplicationContext(servletContext);

    User user = (User)wac.getBean("user");

    But if you are in the business layer, how do you reach the application context? The Spring reference has example of loading the xml file directly. But that is not a good way to do it. I just want to get the context and call getBean.

    Thanks for the help.
    -- Jin

     
    • Jin

      Jin - 2004-08-06

      it could be done with getter and setter in the business service object to any beans it needs to reference to. And in fact if the beans are directly related to the particular service the business object offer in a method, we might just pass in as parameters.

      But then it might be quite busy on the servlet level as it retrieves the business object from the spring's application context and then has to call all the getters and setters so the business service object need reference too.

      I would prefer only getting strictly the beans the business service object needs for business operation and let the business service object resolve other non-critical, cross application objects on its own. To my understand Spring is cross application and provide that bean lookup functionality in all layers.

      On solution I can think of is creating a InitAction that runs at servlet container startup. And it stores the Spring application context in a static object for global access. In this way, all layers can reach the Spring application context and call getBean for whatever bean they want.

      But still I would prefer the Spring framework to provide that functionality. I was a bit surprise it does not have something like ApplicationContextUtil.getContext

       

Log in to post a comment.

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:





No, thanks