tags:

views:

85

answers:

4

How should each class in an application retrieve the Spring application context? Or, stated another way, how many times should an application invoke new ClassPathXmlApplicationContext("applicationContext.xml")?

+5  A: 

Usually a class does not need the application context, but it needs some of the objects Spring injects. And this is configured in that applicationContext.

As such an application typically calls new ClassPathXmlApplicationContext("applicationContext.xml") only once.

extraneon
+3  A: 

With dependency injection, you shouldn't have to, in general. But if your class really needs to be aware of the application context, implement the ApplicationContextAware interface. Spring will automatically call the setApplicationContext method defined in that interface to provide your class with the application context.

Note that if you're trying to gain access to filesystem resources, you should use ResourceLoaderAware. If you want access to the message source, then don't implement an interface; instead, inject a reference to the MessageSource bean.

Jeff
What's wrong with implementing `MessageSourceAware` to get the MessageSource? I've done this for an application and it always worked just fine.
jasonmp85
Nothing terribly wrong, but why implement an interface when all you need to do is pass a reference?
Jeff
+2  A: 

I think you should take the advice from the answer to your other question here. Implementing ApplicationContextAware or ServletContextAware (if you are in a servlet container) is the best way to get the context.

Look up how spring handles Dependency Injection or Inversion of Control.

Peter D
+2  A: 

Once.

Actually you should let Spring do the heavy lifting and build/configure the classes rather than the other way around.

The whole idea is that all classes can be built without having to call the outside world for dependencies, which are 'magically' provided by the Spring framework.

This approach was invented to get away from the ServiceLocator pattern to which you are alluding, i.e. get a reference to an object to get the dependencies you need, ala JNDI.

Peter Tillemans