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

  • Spring ApplicationContext

    Say i initialize the spring IOC container in web.xml as follows..
    some files

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

    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.


    • #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?


      • #4
        You could do that. This thread might be more helpful.