Warning: Parameter 1 to Language::getMagic() expected to be a reference, value given in /home/wikija5/public_html/w/includes/StubObject.php on line 58

Warning: Parameter 3 to renderSEO() expected to be a reference, value given in /home/wikija5/public_html/w/includes/parser/Parser.php on line 3243
Using the Application context in Spring - WikiJava
Friday, 25th July 2014
Follow WikiJava on twitter now. @Wikijava

Using the Application context in Spring

From WikiJava

Jump to: navigation, search
The author suggests:

buy this book


This article shows how to use the Spring Framework in it's most basic usage. We use the ApplicationContext.xml file to define some Java beans so that we can retrieve them in the application. In this way we can reimplement the classes and use alternatively different implementations by just changing the configuration in the ApplicationContext.xml file.

Contents

Why is this useful?

Imagine this situation: you want to develop a program of a decent size. This program is made of different components, which are independent and collaborate to the processing overall.

You can't develop all the components at the same time, but once you finish the first component you're going to need some dummy behaviour from the other components to test it.

What you can do is to create dummy implementations of the other components and wire them using the dependency injection from the Spring Framework. These dummy components will behave pretty much as the component you implemented expects, for example a DAO could return always the same hard coded object. So you can test the component in a pretty much realistic context.

Once you're done with the component, you can start working on the second one and wire it in the applicationContext.xml file. So that to test it you can just switch whatever implementation, without even recompiling the project.

Another situation where you can smoothly use Spring beans is when you have an application which has configurable components. You can deploy the different components by just wiring them in the application context.

For example you may have a software which supports the mySql Database, but you want to deploy it on a system with Oracle. You can simply reimplement the interface creating new DAO's that support Oracle, then just wire them in the application context instead of the MySql DAO's. If you need to switch back to MySql, just rewire the old DAO's and you're done. You don't even need to recompile.

the BatBotResourceFactory Class

For this application I created a Factory class which is also a Singleton called BatBotResourceFactory .

I did this to have a unique place to access the Spring beans, since I consider the beans provided by spring like external resources I don't want my software to be too much dependent on the framework. In the whole program there are no links to Spring, so with this architecture I can easily completely remove the spring framework from my application by just reimplementing the BatBotResourceFactory.


How to get the singleton

The Singleton is simply implemented in the getSingleton method, which is declared public and static:

    private static BatBotResourceFactory batBotResourceFactory;
    public synchronized static BatBotResourceFactory getSingleton() {
	if (null == batBotResourceFactory) {
	    batBotResourceFactory = new BatBotResourceFactory();
	}
	return batBotResourceFactory;
    }
 
    private BatBotResourceFactory() {
	context = new FileSystemXmlApplicationContext(APPLICATION_CONTEXT_FILE);
    }

Note that the constructor for the class is declared private, this is a fundamental requirement for the singleton Class. Note also that the getSingleton method is synchronized.

This is the most normal lazy Singleton in the world.


Initializing the Application Context

Before using the application context we need to instantiate it via the org.springframework.context.support.FileSystemXmlApplicationContext class from the Spring framework. This is an expensive process that involves to open and parse the applicationContext.xml file.

This expensive operation is the reason why I created the factory method and made is as a Singleton.

 private ApplicationContext context;
 
 private static final String APPLICATION_CONTEXT_FILE = "applicationContext.xml";
 
  private BatBotResourceFactory() {
	context = new FileSystemXmlApplicationContext(APPLICATION_CONTEXT_FILE);
    }

obtaining the Beans

Once the org.springframework.context.ApplicationContext is created and saved in the context field. it can be used to retrieve the beans from the Spring framework. At this point it's very simple:

All you need to do is to call the getBean Method

Object org.springframework.beans.factory.BeanFactory.getBean(String name) throws BeansException

The method is used as follows:

 public FileHelperI getFileHelper() {
	return (FileHelperI) context.getBean("fileHelperBean");
    }


the Full code for the class

Image:250px-Subversion.png
You can download the complete code of this article from the Subversion repository at this link

Using the username:readonly and password: readonly

See the using the SVN repository instructions page for more help about this.
/**
 *    This source file is part of BatBot,
 *    Copyright (C) 2008 Giulio Giraldi
 *    Find more details on the BatBot Project at: 
 *    http://www.wikijava.org/wiki/batBot:Main_page
 * 
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 * 
 *   This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 * 
 *    You should have received a copy of the GNU General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.wikijava.network.batBot.delegates;
 
import java.util.logging.Logger;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.wikijava.network.batBot.delegates.interfaces.ActionExecutorI;
import org.wikijava.network.batBot.delegates.interfaces.FileHelperI;
import org.wikijava.network.batBot.delegates.interfaces.HttpHelperI;
 
public class BatBotResourceFactory {
 
    private transient static Logger log = Logger
	    .getLogger(BatBotResourceFactory.class.getName());
 
    private static final String APPLICATION_CONTEXT_FILE = "applicationContext.xml";
 
    ApplicationContext context;
 
    private static BatBotResourceFactory batBotResourceFactory;
 
    public static BatBotResourceFactory getSingleton() {
	if (null == batBotResourceFactory) {
	    batBotResourceFactory = new BatBotResourceFactory();
	}
	return batBotResourceFactory;
    }
 
    private BatBotResourceFactory() {
	context = new FileSystemXmlApplicationContext(APPLICATION_CONTEXT_FILE);
    }
 
    public FileHelperI getFileHelper() {
	return (FileHelperI) context.getBean("fileHelperBean");
    }
 
    public HttpHelperI getHttpHelper() {
	return (HttpHelperI) context.getBean("httpHelperBean");
    }
 
    public ActionExecutorI getActionExecutorI() {
	return (ActionExecutorI) context.getBean("ActionExecutorBean");
    }
 
}

the application context file

Image:250px-Subversion.png
You can download the complete code of this article from the Subversion repository at this link

Using the username:readonly and password: readonly

See the using the SVN repository instructions page for more help about this.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
          "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
	<bean id="fileHelperBean" class="org.wikijava.network.batBot.delegates.XStreamFileHelper">
	</bean>
	<bean id="httpHelperBean" class="org.wikijava.network.batBot.delegates.HttpHelper">
	</bean>
	<bean id="ActionExecutorBean" class="org.wikijava.network.batBot.delegates.ActionExecutor">
	</bean>
</beans>

Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page

Alcor

I'm plannin' to learn Spring and your article is great. Very well written.

Would you please explain me better the uses of the application context file?

--Alcor 16:30, 2 January 2009 (UTC)


Wow, that's an open question

Hi, Wow that's an open question, the application context can define everything within the Spring framework. From AOP to Web MVC to loads of other things. I recommend you a good reading on the Spring framework to get an answer to your question.

--DonGiulio 16:52, 3 January 2009 (UTC)


Santhosh

How can i instantiate Application Context?


--Santhosh 05:34, 18 May 2011 (PDT)


instantiate Application Context

Application Context is an interface, therefore it cannot be instantiated. What you can do is to instantiate one of the (non-abstract) classes that implement the application Context interface. In this example I used:

context = new FileSystemXmlApplicationContext(APPLICATION_CONTEXT_FILE);

but you can instantiate any other of the implementations. You can see a list of the default ones on the man page: here.

Hope this answers your question :)


--DonGiulio 11:35, 19 May 2011 (UTC)


Sunil

Hi I gone through this article.and i found that this is very useful for the begineer

Thanks

--Sunil 02:14, 19 July 2011 (PDT)


Comments on wikijava are disabled now, cause excessive spam.