How should each class in an application retrieve the Spring application context?
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("app开发者_运维问答licationContext.xml")
?
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.
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.
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.
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.
精彩评论