Integrate the Spring Framework into your next Eclipse-based project using Apache Maven. Learn how to install, configure, and integrate these three leading Java development tools. All source code for this post is available on GitHub.
Introduction
Although there is a growing adoption of Java EE 6 and CDI in recent years, Spring is still a well-entrenched, open-source framework for professional Java development. According to GoPivotal’s website, “The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications. Spring focuses on the ‘plumbing’ of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.”
Similar to Spring in terms of wide-spread adoption, Eclipse is leading Java IDE, competing with Oracle’s NetBeans and JetBrain’s IntelliJ. The use of Spring within Eclipse is very common. In the following post, I will demonstrate the ease of integrating Spring with Eclipse, using Maven.
Maven is a marketed as a project management tool, centralizing a project’s build, reporting and documentation. Conveniently, Maven is tightly integrated with Eclipse. We will use Maven for one of its best known features, dependency management. Maven will take care of downloading and managing the required Spring artifacts into our Eclipse-based project.
Note there are alternatives to integrating Spring into Eclipse, using Maven. You can download and add the Spring artifacts yourself, or go full-bore with GoPivotal’s Spring Tool Suite (STS). According to their website, STS is an Eclipse-based development environment, customized for developing Spring applications.
The steps covered in this post are as follows:
- Download and install Maven
- Download and install the Eclipse IDE
- Linking the installed version of Maven to Eclipse
- Creating a new sample Maven Project
- Adding Spring dependencies to the project
- Demonstrate a simple example of Spring Beans and ApplicationContext
- Modify the project to allow execution from an external command prompt
Installing Maven
Installing Maven is simple process, requiring minimal configuration:
- Download the latest version of Maven from the Apache Maven Project website. At the time of this post, Maven is at version 3.1.1.
- Assuming you are Windows, unzip the ‘apache-maven-3.1.1’ folder and place in your ‘Program Files’ directory.
- Add the path to Maven’s bin directory to your system’s ‘PATH’ Environmental Variable.
We can test our Maven installation by opening a new Command Prompt and issuing the ‘mvn -version’ command. The command should display the installed version of Maven, Maven home directory, and other required variables, like your machine’s current version of Java and its location. To learn other Maven commands, try ‘mvn -help’.
Installing Eclipse IDE
Installing Eclipse is even easier:
- Download the latest version of Eclipse from The Eclipse Foundation website. There are several versions of Eclipse available. I chose ‘Eclipse IDE for Java EE Developers’, currently Kepler Service Release 1.
- Similar to Maven, unzip the ‘eclipse’ folder and place in your ‘Program Files’ directory.
- For ease of access, I recommend pinning the main eclispe.exe file to your Start Menu.
Linking Maven to Eclipse
The latest version of Eclipse comes pre-loaded with the ‘M2E – Maven Integration for Eclipse’ plug-in. There is no additional software installs required to use Maven from within Eclipse. Eclipse also includes an embedded runtime version of Maven (currently 3.04). According to the Eclipse website wiki, the M2E plug-in uses the embedded runtime version of Maven when running Maven builder, importing projects and updating project configuration.
Although Eclipse contains an embedded version of Maven, we can configure M2E to use our own external Maven installation when launching Maven using Run as… -> M2 Maven actions. To configure Maven to use the version of Maven we just installed:
- Go to Windows -> Preferences -> Maven -> Installations window. Note the embedded version of Maven is the only one listed and active.
- Click Add… and select the Maven folder we installed in your Program Files directory. Click OK.
- Check the box for new installation we just added instead of the embedded version. Click OK.
Sample Maven Project
To show how to integrate Spring into a project using Maven, we will create a Maven Project in Eclipse using the Maven Quickstart Archetype template. The basic project will show the use of Spring Beans and an ApplicationContext IoC container. On a scale of 1 to 10, with 10 being the most complex Spring example, this project is barely a 1! However, it will demonstrate that Spring is working in Eclipse, with minimal effort thanks to Maven.
To create the project:
- File -> New Project -> Other…
- Search on ‘maven’ in the Wizards text box and select ‘Maven Project’.
- Select the Maven Quickstart Archetype.
- Specify the Archetype parameters.
Spring Dependencies
Once the Maven Quickstart project is created, we will add the required Spring dependencies using Maven:
- Open the Maven Project Object Model (POM) file and select the Dependencies tab.
- Use the The Central Repository website to find the Dependency Information for spring-core and Spring-context artifacts (jar files).
- Add… both Spring Dependencies to the pom.xml file.
- Right-click on the project and click Maven -> Update Project…
We now have a Maven-managed Eclipse project with our Spring dependencies included. Note the root of the file paths to the jar files in the Maven Dependencies project folder is the location of our Maven Repository. This is where all the dependent artifacts (jar files) are stored. In my case, the root is ‘C:\Users\{user}\.m2\repository’. The repository location is stored in Eclipse’s Maven User Setting’s Preferences (see below).
Project Object Model File (pom.xml):
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | |
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> | |
<modelVersion>4.0.0</modelVersion> | |
<groupId>com.blogpost.maven</groupId> | |
<artifactId>maven-spring</artifactId> | |
<version>0.0.1-SNAPSHOT</version> | |
<packaging>jar</packaging> | |
<name>maven-spring</name> | |
<url>http://maven.apache.org</url> | |
<properties> | |
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> | |
</properties> | |
<dependencies> | |
<dependency> | |
<groupId>junit</groupId> | |
<artifactId>junit</artifactId> | |
<version>3.8.1</version> | |
<scope>test</scope> | |
</dependency> | |
<dependency> | |
<groupId>org.springframework</groupId> | |
<artifactId>spring-core</artifactId> | |
<version>3.2.4.RELEASE</version> | |
</dependency> | |
<dependency> | |
<groupId>org.springframework</groupId> | |
<artifactId>spring-context</artifactId> | |
<version>3.2.4.RELEASE</version> | |
</dependency> | |
</dependencies> | |
<description>Project for blog post about the use of Spring with Eclipse and Maven.</description> | |
</project> |
Sample Code
Next add the supplied Code to the project. We will add two new java classes and a Spring configuration file. We will replace the contents of main App class with our sample code. Steps are as follows:
- Add the supplied Vehicle.java and MaintainVehicle.java class files to the project, in the same classpath as the App.java class.
- Add the supplied Beans.xml Spring configuration file to the project at the ‘src/main/java’ folder.
- Open the App.java class file and replace the contents with the supplied App.java class file.
The sample Spring application is based on vehicles. There are three Spring Beans defined in the xml-based Spring configuration file, representing three different vehicles. The main App class uses an ApplicationContext IoC Container to instantiate three Vehicle POJOs from the Spring Beans defined in the Beans.xml Spring configuration. The main class then instantiates an instance of the MaintainVehicle class, passes in the Vehicle objects and calls MaintainVehicle’s two methods.
Spring Configuration File (Beans.xml):
<?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-3.0.xsd"> | |
<bean id="vehicle1" class="com.blogpost.maven.maven_spring.Vehicle"> | |
<property name="make" value="Mercedes-Benz" /> | |
<property name="model" value="ML550" /> | |
<property name="year" value="2010" /> | |
<property name="color" value="Silver" /> | |
<property name="type" value="SUV" /> | |
</bean> | |
<bean id="vehicle2" class="com.blogpost.maven.maven_spring.Vehicle"> | |
<property name="make" value="Jaguar" /> | |
<property name="model" value="F-Type" /> | |
<property name="year" value="2013" /> | |
<property name="color" value="Red" /> | |
<property name="type" value="Convertible" /> | |
</bean> | |
<bean id="vehicle3" class="com.blogpost.maven.maven_spring.Vehicle"> | |
<property name="make" value="Suzuki" /> | |
<property name="model" value="SVF 650" /> | |
<property name="year" value="2012" /> | |
<property name="color" value="Black" /> | |
<property name="type" value="Motorcycle" /> | |
</bean> | |
</beans> |
Main Method Class (App.java)
package com.blogpost.maven.maven_spring; | |
import org.springframework.context.ApplicationContext; | |
import org.springframework.context.support.ClassPathXmlApplicationContext; | |
public class App { | |
public static void main(String[] args) { | |
@SuppressWarnings("resource") | |
ApplicationContext context = new ClassPathXmlApplicationContext( | |
"Beans.xml"); | |
MaintainVehicle maintain = new MaintainVehicle(); | |
// vehicle1 bean | |
Vehicle obj1 = (Vehicle) context.getBean("vehicle1"); | |
System.out.printf("I drive a %s.\n", obj1.getLongDescription()); | |
System.out.printf("Is my %s tuned up? %s\n", | |
obj1.getShortDescription(), obj1.getServiced()); | |
maintain.serviceVehicle(obj1); | |
System.out.printf("Is my %s tuned up, yet? %s\n\n", obj1.getMake(), | |
obj1.getServiced()); | |
// vehicle2 bean | |
Vehicle obj2 = (Vehicle) context.getBean("vehicle2"); | |
System.out.printf("My wife drives a %s.\n", obj2.getLongDescription()); | |
System.out.printf("Is her %s clean? %s\n", obj2.getShortDescription(), | |
obj2.getWashed()); | |
maintain.washVehicle(obj2); | |
System.out.printf("Is her %s clean, now? %s\n\n", obj2.getMake(), | |
obj2.getWashed()); | |
// vehicle3 bean | |
Vehicle obj3 = (Vehicle) context.getBean("vehicle3"); | |
System.out.printf("Our son drives his %s too fast!\n", obj3.getType() | |
.toLowerCase()); | |
} | |
} |
Running the Application
If successful, the application will output a series of messages to the Console. The first few messages in red are Spring-related messages, signifying Spring is working. The next messages in black are output by the application. The messages show that the three Spring Beans are successfully instantiated and passed to the MaintainVehicle object, where it’s methods were called. If the application would only buy me that Silver Mercedes!
Running the Application from a Command Prompt
All the source code for this project is available on GitHub. Note the pom.xml contains a some extra configuration information not shown above. The extra configuration information is not necessary for running the application from within Eclipse. However, if you want to run the application from an external Command Prompt, you will need the added configuration. This extra configuration ensures that the project is correctly packaged into a jar file, with all the necessary dependencies to run. Extra configuration includes an additional logging dependency, a resource reference to the Spring configuration file, one additional property, and three maven plug-in references for compiling and packaging the jar.
To run the java application from an external Command Prompt:
- Open a new Command Prompt
- Change current directory to the project’s root directory (local GitHub repository in my case)
- Run a ‘mvn compile’ command
- Run a ‘mvn package’ command (downloads dependencies and creates jar)
- Change the current directory to the project’s target sub-directory
- Run a ‘dir’ command. You should see the project’s jar file
- Run a ‘java -jar {name-of-jar-file.jar}’ command.
You should see the same messages output in Eclipse, earlier.
#1 by SutoCom on October 23, 2013 - 2:48 am
Reblogged this on Sutoprise Avenue, A SutoCom Source.
#2 by Marco R on June 27, 2014 - 9:27 pm
Thamks! a good start point for understanding maven functionality
#3 by Evgheni on September 12, 2014 - 8:37 am
Thank you for such clearly explained tutorial!
#4 by Stanley on November 13, 2014 - 9:09 pm
It’s a very good tutorial.
Thank you for the work!
#5 by Maik on January 7, 2015 - 6:23 am
Muy bueno! It’s the first baby steps to start I helped me to understand. Thanks
#6 by sethisan on August 5, 2015 - 3:18 pm
This helped me get started with my new job — thanks a lot!
#7 by Manoj Nautiyal on March 5, 2016 - 2:16 pm
Very helpful tutorial ! Nicely explained steps along with a good example – I was able to get my first spring application configured with maven and get it running straightaway. Otherwise I had a tough time going through many other blogs.
#8 by Rahul on March 25, 2016 - 1:57 am
Very nicely written.Simple and intuitive.Thanks 🙂
#9 by sairam on January 24, 2018 - 7:15 pm
It is a very useful tutorial. It made many things easy for me. It is what exactly I wanted.