Srikanth Technologies

Getting Started With Spring Framework

In this blog, I show how to get started with Spring Framework. As there are many ways to get started, I show a simple and light-weight way to get started.

Creating Project

Follow the steps below to create a new project that uses Spring Framework and Maven.

  1. Install STS (Spring Tool Suite). It is recommended IDE. If you have ever worked with Eclipse, you find it very easy to use as it is extension of Eclipse. Download STS from https://spring.io/tools/sts. Extract downloaded zip file to a folder and it creates sts-bundle folder. Inside that folder you find sts-3.8.3.RELEASE (current version as of this writing) folder, which contains STS.exe. Run STS.EXE to start STS.
  2. STS looks and works very much like Eclipse. Create a new project by selecting File -> New -> Spring Legacy Project.
  3. Select Simple Spring Maven as template and enter springdemo as project name.
  4. STS creates a simple Java project that uses Maven. Maven takes care of downloading required dependencies. Maven is indispensible when working with frameworks like Spring as it downloads all required JAR files from Maven Central Repository for all dependencies mentioned in POM (project object model) file.
  5. Modify POM.XML as follows so that we include only required dependencies and also change Java version to 1.8.

    
    <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>st.com</groupId>
    	<artifactId>springdemo</artifactId>
    	<version>1.0-SNAPSHOT</version>
    
    	<properties>
    		<!-- Generic properties -->
    		<java.version>1.8</java.version>
    		<!-- Spring -->
    		<spring-framework.version>4.3.3.RELEASE</spring-framework.version>
    	</properties>
    
    	<dependencies>
    		<!-- Spring and Transactions -->
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-context</artifactId>
    			<version>${spring-framework.version}</version>
    		</dependency>
    	</dependencies>
    	
    	<build>
    		<finalName>springdemo</finalName>
    		<plugins>
    			<plugin>
    				<groupId>org.apache.maven.plugins</groupId>
    				<artifactId>maven-compiler-plugin</artifactId>
    				<version>3.3</version>
    				<configuration>
    					<source>${java.version}</source>
    					<target>${java.version}</target>
    				</configuration>
    			</plugin>
    		</plugins>
    	</build>
    	
    </project>
    
            
  6. Update project with changes to POM file using ALT+F5. It will ask you for confirmation, click on OK. Alternatively you can select same option by righ click on project and selecting Maven -> Update Project option.
  7. As Maven downloaded all required libraries, we are all set to write code using Spring Framework.

Implement Dependency Injection

One of the pillars on which Spring Framework is built is Dependency Injection. In the following snippets we see how to write code that implements DI.

Books.java

This interface is implemented by beans. Spring strongly recommends programming to interfaces. So let us create an interface - Books.

import java.util.List;

public interface Books {
 	   List<String> getBooks();	 
}

JavaBooks.java

Implement Books interface and provide implementation for methods.


import java.util.ArrayList;
import java.util.List;

public class JavaBooks implements Books {
	@Override
	public List<String> getBooks() {
		ArrayList<String> books = new ArrayList<String>();

		books.add("Java Complete Reference");
		books.add("Spring in Action");
		return books;
	}
}

Catalog.java

This is another bean that depends on a bean that implements Books interface. It uses what is called as setter dependency injection as it uses setter method to inject dependency.


public class Catalog {
	private Books books;

	public void setBooks(Books books) {
		this.books = books;
	}

	public void print() {
		for (String book : books.getBooks()) {
			System.out.println(book);
		}
	}
 }

Beans.xml

Metadata about Spring Beans can be provided in different ways. For now, I am using XML file to provide metadata.

Add Bean Configuration file by right clicking on project and selecting New -> Bean Configuration File. When prompted, enter name beans.xml and click on Next and then Finish.

A new empty configuration file is created. Add details about beans as follows:


<?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="javabooks" class="JavaBooks" />
	<bean id="catalog" class="Catalog">
		<property name="books" ref="javabooks"></property>
	</bean>
</beans>

Application.Java

Final component is Application class, which contains main method. It creates an object of ClassPathXmlApplicationContext (Bean Container) and provides beans.xml as file to be used to get information about beans. Spring container creates beans whose information is provided in beans.xml. It uses getBean() of container to get access to catalog bean. Catalog bean depends on Books bean. The dependency is resolved by injecting JavaBooks, which is a match to Books as it implements Books interface.


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Application {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

		Catalog cat = context.getBean("catalog", Catalog.class);
		cat.print();
	}
}

Save all files and run Application.java to get the output shown in the screenshot below.

You can see also the structure of springdemo project in Package Explorer.