Learning Spring Application Development - Sample Chapter
Learning Spring Application Development - Sample Chapter
ee
Sa
pl
Learning Spring
Application Development
The Spring Framework is a cutting-edge framework that provides comprehensive
infrastructure support for developing Java applications. The Spring Framework
handles the infrastructure so that you can focus on your application. It promotes
good programming practice by enabling a POJO-based programming model and
also provides a good way to structure your application into layers. It is the appropriate
time for you to understand how to best leverage the Spring Framework to create highperforming, easily testable, reusable code when architecting, designing, and developing
large-scale Java development projects.
Some of you prefer learning by reading, while others prefer learning by coding.
I believe that learning by coding results in better learning, which is what I've done
in this book. There is plenty of example code and adequate textual description to
help you grasp each Spring Framework feature presented. From the very first
chapter, you will be able to develop an application using the Spring Framework.
The Spring Framework is an ocean with a number of features. This book covers
a lot of commonly used features in applications and has taken care to present
code-based examples for every feature. The book is replenished with tons of
code and diagrams. Extra effort has been taken to present snapshots of the
libraries used in every example and output. For more information about this
book, visit http://learningspringapplicationdevelopment.com/
Introducing the
Spring Framework
In this chapter, we'll introduce you to the Spring Framework. We'll also summarize
some of the other features of Spring. We'll then discuss the Spring Architecture as
well as the benefits of the Spring Framework. We will create your first application
in Spring and will look into understanding the packaging structure of the Spring
Framework. This chapter serves as a road map to the rest of this book.
The following topics will be covered in this chapter:
Introducing Spring
[1]
As the title implies, we introduce you to the Spring Framework and then explore
Spring's core modules. Upon finishing this chapter, you will be able to build a
sample Java application using Spring. If you are already familiar with the Spring
Framework, then you might want to skip this chapter and proceed straight to
Chapter 2, Inversion of Control in Spring.
Introducing Spring
Spring is a lightweight Inversion of Control (IoC) and aspect-oriented container
framework. Historically, it was created to alleviate the complexity of the then J2EE
standard, often giving an alternative model. Any Java EE application can benefit
from the Spring Framework in terms of simplicity, loose coupling, and testability.
It remains popular due to its simple approach to building applications. It also
offers a consistent programming model for different kinds of technologies, be they
for data access or messaging infrastructure. The framework allows developers to
target discrete problems and build solutions specifically for them.
The Spring Framework provides comprehensive infrastructure support for
developing Java EE applications, where the Spring Framework handles the
infrastructure and so developers can focus on application development.
Considering a scenario of JDBC application without using the Spring Framework,
we have a lot of boilerplate code that needs to be written over and over again to
accomplish common tasks. Whereas in Spring JDBC application, which internally
uses plain JDBC, the JdbcTemplate class eliminates boilerplate code and allows
the programmer to just concentrate on application-specific logics development.
[2]
Chapter 1
For a Spring JDBC application (internally uses plain JDBC), follow these steps:
1. Get access to JdbcTemplate.
2. Prepare and execute an SQL query.
3. Gather and process the result.
[3]
Features of Spring
The Spring Framework contains the following features:
[4]
Chapter 1
[5]
Spring MVC Framework: This helps in building robust and maintainable web
applications. It uses IoC that provides separation of controller logic. Spring
MVC Framework, which is a part of the Spring Framework licensed under the
term of Apache license, is an open source web application framework. Spring
MVC Framework offers utility classes to handle some of the most common
tasks in web application development. We'll discuss more about Spring Web
MVC Framework in Chapter 5, Spring Web MVC Framework.
[6]
Chapter 1
Spring Batch: This is useful when it's necessary to perform bulk operations
on data. For more information, refer to http://static.springsource.org/
spring-batch.
Spring Framework 1.0: This version was released on March 2004, and the
first release was Spring Framework 1.0 RC4. The final and stable release was
Spring Framework 1.0.5. Spring 1.0 was a complete Java/J2EE application
framework, which covered the following functionalities:
Spring Framework 2.X: The Spring Framework 2.0 was released in October
2006 and Spring 2.5 was released in November 2007. The Spring Framework
2.x release was based around two themes: simplicity and power. This
provides you with the following features:
Spring Framework 3.0: This version was released in December 2009. It makes
the entire Spring code base to take advantage of the Java 5.0 technology.
This provides you with the following features:
[8]
Chapter 1
[9]
[ 10 ]
Chapter 1
Core module: This module of Spring Core Container is the most important
component of the Spring Framework. It provides features such as IoC and
Dependency Injection. The idea behind IoC is similar to the Hollywood
principle: "Don't call me, I'll call you." Dependency Injection is the basic
design principle in Spring Core Container that removes explicit dependence
on container APIs.
[ 11 ]
[ 12 ]
Chapter 1
Data access/integration
Spring's data access addresses common difficulties developers face while working
with databases in applications.
OXM module: Spring OXM module stands for Spring Object XML Mappers,
which supports Object/XML mapping. It also supports integration with
Castor, JAXB, XmlBeans, and the XStream framework.
Most applications need to integrate or provide services to other applications.
One common requirement is to exchange data with other systems, either on
a regular basis or in real time. In terms of the data format, XML is the most
commonly used format. As a result, there exists a common need to transform
a JavaBean into XML format and vice versa.
Spring supports many common Java-to-XML mapping frameworks
and, as usual, eliminates the need for directly coupling to any specific
implementation. Spring provides common interfaces for marshalling
(transforming JavaBeans into XML) and unmarshalling (transforming
XML into Java objects) for DI into any Spring beans. Spring also has
modules to convert data to and from JSON, in addition to OXM.
Servlet module: In Spring, the Servlet module contains Model-ViewController (MVC) implementation that helps to build enterprise web
applications. In Spring Framework, the MVC provides clean separation
between binding request parameter, business objects, and controller logic.
Chapter 1
It is modular, allowing you to use only those parts that you need. It allows
us to just choose any part of it in isolation.
The Spring Web MVC framework provides powerful and a flexible Web
framework as an alternative to Struts and other framework.
Download the package and extract it. Under the lib folder, you will find a
list of Spring JAR files that represents each Spring module.
[ 15 ]
Checking Spring out of GitHub: You can check out the latest version of
code from Spring's GitHub repository at https://github.com/springprojects/spring-framework.
To check out the latest version of the Spring code, first install Git
from http://git-scm.com/, open the Git Bash tool, and run the
following command:
git clone https://github.com/spring-projects/spring-framework
[ 16 ]
Chapter 1
[ 17 ]
2. Name your Spring project SimpleSpringProject and select the Simple Java
template, which creates a Simple Spring project using the Java build without
a top-level package and with default Spring configuration and project
natures, as shown in the following screenshot:
[ 18 ]
Chapter 1
[ 19 ]
menu, that is, Build Path | Configure Build Path to display the Java Build
Path window, as shown in the following screenshot:
2. Now, use the Add External JARs button from the Libraries tab in order to
include the following core JARs from the Spring Framework and common
logging installation directories:
spring-aop-4.1.4.RELEASE
spring-aspects-4.1.4.RELEASE
spring-beans-4.1.4.RELEASE
spring-context-4.1.4.RELEASE
[ 20 ]
Chapter 1
spring-context-support-4.1.4.RELEASE
spring-core-4.1.4.RELEASE
spring-expression-4.1.4.RELEASE
commons-logging-1.2
[ 21 ]
Now, you will have the content in your Project Explorer, as shown in the
following screenshot:
[ 22 ]
Chapter 1
[ 23 ]
GreetingMessageService.java:
package org.springframework.chapter1.service;
public interface GreetingMessageService {
public String greetUser();
}
GreetingMessageServiceImpl.java:
package org.springframework.chapter1.service;
import org.springframework.stereotype.Service;
@Service
public class GreetingMessageServiceImpl implements
GreetingMessageService {
public String greetUser() {
return "Welcome to Chapter-1 of book Learning
Spring Application Development";
}
}
Chapter 1
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.
ClassPathXmlApplicationContext;
public class MainClass {
public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext(
"beans.xml");
GreetingMessageService greetingMessageService =
context.getBean(
"greetingMessageServiceImpl",
GreetingMessageService.class);
System.out.println(greetingMessageService.greetuser());
}
}
This API loads Spring beans configuration file named beans.xml, which takes care
of creating and initializing all the bean objects. We use the getBean() method of the
created ApplicationContext to retrieve required Spring bean from the application
context, as shown in the following:
GreetingMessageService greetingMessageService = context.getBean(
"greetingMessageServiceImpl", GreetingMessageService.class);
The getBean() method uses bean ID and bean class to return a bean object.
[ 25 ]
2. Enter the bean name beans and click on Next, as shown in the
following screenshot:
[ 26 ]
Chapter 1
4. Now the Spring bean configuration file is created. Add the following code
to create an entry. The contents of the beans.xml file are 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"
[ 27 ]
When the Spring application gets loaded into the memory, in order to create all
the beans, the framework uses the preceding configuration file, as shown in the
following screenshot:
The Spring bean configuration file can be named anything, but developers usually
keep the name beans.xml. This Spring bean configuration file should be available
in classpath.
The S in the upper-right corner of the project icon indicates
it is a Spring Project.
[ 28 ]
Chapter 1
We have successfully created our first Spring application, where you learned how to
create the Spring project and executed it successfully. We will see detailed examples
in the next chapter.
Exercise
Q1. What is Spring?
Q2. List some of the features of Spring.
Q3. Explain different modules in the Spring Framework.
Summary
In this chapter, you were introduced the Spring Framework and acquainted with its
features. You took a look at the versions of Spring. Then, you studied the architecture,
and different modules in the Spring Framework such as the Spring Core Container,
Spring AOP, Spring data access/integration, and the Spring Web module and Test
module. You also understood the benefits of the Spring Framework. Finally, you
created an application in Spring and took a look on package structure of Spring.
In the next chapter, we'll explore IoC, Dependency Injection, and Spring Core
Container service. We'll also see bean's life cycle and bean's scope.
[ 29 ]
www.PacktPub.com
Stay Connected: