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

  • Spring ApplicationContext

    Say i initialize the spring IOC container in web.xml as follows..
    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
    some files
    </param-value>
    </context-param>

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

    How can i programmatically get a reference to that instance of ApplicationContext.. or better yet to the beans i defined in the list of files.

    Only way i know of is to..
    appCtx = new ClassPathXmlApplicationContext(SPRING_XML_FILES);
    BeanFactory factory = (BeanFactory) appCtx;
    SomeObject o = (SomeObject) appCtx.getBean("somebean");

    But then im just duplicating code.

    Whats the point of setting it up in web.xml then if i just have to put int he config files again?

    Is there some static method like Spring.getCurrentInstance or ApplicationContext.getCurrentInstance etc.....

  • #2
    It's very rare you need a reference to the applicationContext in your code. If you do, you could use WebApplicationContextUtils or ApplicationContextAware. You might also want to have a read of the end of chapter 3.
    http://www.springframework.org/docs/...textUtils.html
    http://www.springframework.org/docs/...onality-events
    http://www.springframework.org/docs/...context-create

    Comment


    • #3
      I've read that whole chapter but i guess im still missing something.

      Say i have object A that is managed by spring and i inject some object b and c into a.

      Now somewhere in my code i want to use object a. How do i get a reference to object a that has be initiliazed via spring? I obviously cant do: A a = new A(); Instead i need some way to pull it from the context like context.getBean("a");

      So now you may say just inject object A into the object that needs it. But then how do i get a reference to that object?

      Second: Say i use ApplicationContextAware and that object is injected with the ApplicationContext. How do i get that object? Should i create a static method getApplicationContext that retrieves the context?

      public class Whatever() implements ApplicationContextAware {

      private static ApplicationContext ctx = null;

      public setApplicationContext(ApplicationContext context) {
      ctx = context;
      }

      public static getApplicationContext() {
      return ctx;
      }

      }

      Is this correct?

      Comment


      • #4
        You could do that. This thread might be more helpful.
        http://forum.springframework.org/showthread.php?t=27884

        Comment

        Working...
        X