This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
I am used to calling the application.xml from main class(public static void main). In any web application I used to load the data in the xxx-servlet.xml instead of accessing the bean. Now as i am developing an application, I am not getting where to declare the Application context to access the beans. If I am in the DAO layer I have to declare the "ApplicationContext ctx = new ClassPath....()" in the dao class to access the beans related to dao tasks. If I am in the business layer I have to declare the application context in each of the business classes to access the beans related to business tasks. If this is the case I have got to access the application context in almost all the classes which is Weird. Could someone please guide me how to proceed and guide me if there is any mistake in my approach towards dealing the issue. Thanks in advance.
First, let me correct what Hitesh said: When you do DI in Spring, setter injection with XML configuration files is just *ONE OF MANY* ways. Spring has long supported constructor injection as well. And with recent versions of Spring (starting with 2.5) you can @Autowire inject into virtually anything (setter method, constructor argument, arbitrary method argument, private member variable, etc). And with even newer Spring versions (3.0 and 3.1) you can ditch the XML and use Java-based configuration instead of XML.
Now to the original question: If you're doing a web application layered as you describe, there's no need to load up the application context everytime you need it...in fact, that would most definitely be the *wrong* way to do it.
Spring's DispatcherServlet and ContextLoaderListener can load their application contexts *once* given a set of configuration files (either XML or Java-based configuration). You need never worry about actually loading the application context manually. The context will be loaded up, the beans created, and their dependencies injected.
Really, the only time you create and load your own application context is when writing a small application within a main() method. But knowing how to do that as a beginner helps you understand the basics of Spring. Once you advance past the basics, you'll rely less on those application context classes directly and just count on the framework (via DispatcherServlet and ContextLoaderListener) to load the context for you.