Home > Developing Spring Application in Eclipse IDE > Developing Spring Application in Eclipse IDE

Developing Spring Application in Eclipse IDE

 

 

Spring Application Example:


Now that we have installed SpringIDE in Eclipse, let’s explore what we can do using Spring IDE and also create a Spring application. By integrating Spring IDE, we now have a Spring Project Wizard in the New Project option of Eclipse Workbench. We will start our Spring application with a demo project namely springide-demo. This is just to explore the SpringIDE features in Eclipse and not a tutorial on Spring application. This will help in getting started with our detailed tutorial ‘Exploring Spring Framework’ Series.

 

1. Creating a Spring Project:

  • Open the New project dialog box by choosing File Menu > New and Choose Spring Project below in the Wizard.

  • You will see the New Spring Project Dialog wizard. Here type the project name as “springide-demo” and keep all the options at their default values and click the Finish button.

  • This will create a new Spring Project. SpringIDE provides visual indicators in the Package Explorer view which will be shown in Java Perspective. Note the S symbol upon the project name. This is to indicate that this is a Spring project.

 

 

2. Create a working package and class in the project:

  • Create a package namely “com.vehicles” and a class in this package namely “Honda” with two private variables and their setter and getter methods in the project that we created. Find the entire source code in the pdf below or download springide-demo.zip from the box widget on the sidebar.
/**
 *
 */
package com.vehicles;

/**
 * @author Rajani Ramsagar
 *
 */
public class Car {

	private String name;

	private int cost;

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name
	 *            the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the cost
	 */
	public int getCost() {
		return cost;
	}

	/**
	 * @param cost
	 *            the cost to set
	 */
	public void setCost(int cost) {
		this.cost = cost;
	}

}
  • This class is a Plane Old Java Object (POJO). Spring Framework leverages the use of POJO. This POJO will be injected in our application through the bean definition file taht we will see in a while from now. This is how the package structure will look like:

  

 

3. Create Spring definition file:

  • Spring IDE provides a wizard for creation of bean configuration file. Choose the New options in the File menu and the Other option to select the Spring Bean Definition to start the Spring Bean configuration wizard.

  • New Spring Bean Definition file dialog will be shown where you will have to type a name for the bean definition / configuration file. Type name carDemo-beans.xml in the File Name. keep the default options and click Next to proceed.

  • The spring bean definition file wizard includes the XSD namespace (Xml Schema Definition – which is required for validating the bean-definition xml file) by default while creating the template in the previous step. For additional schemas you will have to choose the schema from the given list of available spring schemas. We will keep all the options unchecked as we want to write a simple spring beans application which requires only the core XSD namespace. Click Next.

  • The spring bean definition file wizard provides a way to add the newly created bean definition file in any of the existing config sets. Config set is a Spring IDE way to logically group the bean definition files. We don’t have any config sets created yet so this box is empty. Now click the Finish button to obtain the basic bean definition template.

  • The bean definition wizard will create our carDemo-beans.xml bean definition file, the code can be seen upon clicking the source tab as shown below. The topmost <beans> element is already added to the bean definition file. Now we will have to add our required <bean> definitions to make use of this file.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
  • Spring IDE extends the functionality of the XML editor in Eclipse. The carDemo-beans.xml can be visualized in the XML editor by clicking on the Design tab and can be edited using the visual tabular elements. We can also type elements directly in the Source tab of the editor.

  • We can add elements through the outline view by right clicking on the elements and choosing Attribute or Child option to create a new Attribute or new Child element.

  • At times, you might want to use visual editor or stick with source editing as most of us do. One important feature provided by the Spring IDE is code completion (CTRL+Spacebar keyboard shortcut to invoke the code completion feature) in the source editing of bean definition file . Let us add one bean definition for our Car POJO class as shown below.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="car" class="com.vehicles.Car">
		<property name="name" value="Honda"></property>
		<property name="cost">
			<value>2500000</value>
		</property>
	</bean>
</beans>

 

4. Set classpath by adding Spring Framework Dependencies:

  • For this project to work we will need Spring Framework dependencies. The JAR files needed in the classpath of this project to run this project are: commons-logging.jar (Spring framework internally uses commons-logging API and so we will need this file as a dependency for the spring.jar. This file is available in the lib/jakarta-commons directory of the spring distribution folder), spring.jar (spring core classes available in the dist directory of the spring distribution folder), log4j-1.2.14.jar (We will use Log4j for the logging purposes. If we don’t include this jar then Spring will default to Java logging mechanism through the commons-logging API. With this jar the log4j mechanism will be plugged to the commons-logging API. This file is available in the lib/log4j directory of the spring distribution folder ).
  • Right click the project name in the project explorer view and choose New > Folder option. Give name “lib” to the folder. This will create a folder named lib in the main project directory. Add these three JAR files in the project in the lib directory through local file system (copy-paste them). Select all the three files and right click on them. On the context menu choose Build path > Add to build path option. This will show all the libraries in the referenced Libraries node of the project explorer view to indicate that these files have been added to the build path.

 

 

 

5. Viewing Bean Definitions in Spring Explorer:

  • Spring IDE has provided a separate Spring Explorer to show only spring related artifacts. To see the Spring Explorer right click on the demo-beans.xml bean definition file and choose the Spring Explorer option from the Show In option.

  • Once the Spring Explorer opens, drag and drop it to any location in Eclipse you like. Expand the nodes of the bean definition file in the Spring Explorer view and explore the nodes and attributes available and how its presented in this explorer.

 

 

 

6. Bean Cross Reference View:

  • You can see the bean definitions in a cross referenced way through the beans cross reference view. To open this view choose the Windows Menu, Show View option and selecting the Beans Cross Reference view.

  • Bean Cross Reference View will not show anything unless you use the “link with editor” button available on the view top right portion of the bean cross reference window.

 

 

 

7. Graphical representation of Spring Beans

  • Spring IDE provides a Graphical Visualizer for the bean definitions. Right click the demo-beans.xml file shown in Spring Explorer and choose “Open Graph” option from the menu.

  • Graph view for the beans definition file will be shown in the editor panel of the Eclipse Workbench. This graphical representation provides a picturorial representation of the complete bean definition file.
  • Let us add one more POJO to our project. This time we will write a class namely ShowRoom class which references our Car class as shown below:

/**
 *
 */
package com.vehicles;

/**
 * @author Rajani Ramsagar
 *
 */
public class ShowRoom {

	private Car mediumCars;

	private Car bigCars;

	/**
	 * @return the mediumCars
	 */
	public Car getMediumCars() {
		return mediumCars;
	}

	/**
	 * @param mediumCars
	 *            the mediumCars to set
	 */
	public void setMediumCars(Car mediumCars) {
		this.mediumCars = mediumCars;
	}

	/**
	 * @return the bigCars
	 */
	public Car getBigCars() {
		return bigCars;
	}

	/**
	 * @param bigCars
	 *            the bigCars to set
	 */
	public void setBigCars(Car bigCars) {
		this.bigCars = bigCars;
	}

}
  • ShowRoom class has two properties of Car type namely bigCars and smallCars. We want these properties to be injected from the spring mechanism through the bean definition file. So we configure them in our carDemo-beans.xml shown below:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="car" class="com.vehicles.Car">
		<property name="name" value="Honda"></property>
		<property name="cost">
			<value>2500000</value>
		</property>
	</bean>

	<bean id="showRoom" class="com.vehicles.ShowRoom">
		<property name="bigCars">
			<ref bean="car" />
		</property>
		<property name="mediumCars">
			<bean class="com.vehicles.Car">
				<property name="name">
					<value>Hyundai</value>
				</property>
				<property name="cost">
					<value>500000</value>
				</property>
			</bean>
		</property>
	</bean>
</beans>
  • You can see in the above code, that we have our Car bean from before and another bean configuration now added to the configuration file. This is our new bean ShowRoom whose bigCar property refers to our Honda, and another property mediumCar has a inner – bean declared. These are early days to discuss the beans and we will cover all of them in detail in later posts.
  • Let us add a launcher class with a main method to invoke the BeanFactory (container). We will add SpringDemoApp class for this purpose.
/**
 *
 */
package com.vehicles;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

/**
 * @author Rajani Ramsagar
 *
 */
public class SpringDemoApp {

	private static final Logger logger = Logger.getLogger(SpringDemoApp.class);

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(
				"carDemo-beans.xml"));

		ShowRoom showRoom = (ShowRoom) beanFactory.getBean("showRoom");

		logger.info("Big Cars: " + showRoom.getBigCars().getName());
		logger.info("Medium Cars: " + showRoom.getMediumCars().getName());

	}

}
  • The main method obtains a BeanFactory reference through the XmlBeanFactory class. We pass ClassPathResource object which takes our bean definition file as parameter. But make sure that carDemo-beans.xml is directly under src folder of your project, this way it will be avialable in the classpath and spring framework will locate it automatically through the class path searching mechanism.
  • We will need a minimal log4j.xml file to define the way we want the output of the application to be presented. Let us add a log4j.xml file to the src folder of the project as well.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration PUBLIC
		"http://logging.apache.org/log4j/docs/api/org/apache/log4j/xml/log4j.dtd"
		"http://logging.apache.org/log4j/docs/api/org/apache/log4j/xml/log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

	<appender name="console" class="org.apache.log4j.ConsoleAppender">
		<layout class="org.apache.log4j.SimpleLayout" />
	</appender>

	<root>
		<level value="info" />
		<appender-ref ref="console" />
	</root>

</log4j:configuration>
  • Note the level of the root element is kept at INFO for demonstration purpose. We will see about log4j in later posts to come. For now this will display informational messages. Running this class as a Java Application will provide output as shown below:
INFO - Loading XML bean definitions from class path resource [carDemo-beans.xml]
INFO - Big Cars: Honda
INFO - Medium Cars: Hyundai

 

The following pdf has the source code for this sample Spring application. You can either download this, or download the entire source code springide-demo.zip from the box widget on the sidebar. 

 

 

 

 

Note:

  • To some of you who haven’t got an opportunity to get hands-on with Spring, this post might probably seem a bit overwhelming. This was just a demo application to get started with a Spring application in Eclipse. We will learn every bit of it in posts to come.
  • Refer to other posts in Spring Framework category for further knowledge.

 

 

Advertisements
  1. pankaj
    March 19, 2012 at 6:25 pm

    thankq boss…!!

  2. mallik
    May 9, 2011 at 12:02 pm

    everything is good, eclipse contain lot of version, can u please tell us which eclipse version u have used, becuse in myEclipse ide i dont have the option create spring project directly. thank u.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: