ADVANCED JAVA
This spring tutorial provides in-depth concepts of Spring Framework
with simplified examples. It was developed by Rod Johnson in 2003.
Spring framework makes the easy development of JavaEE application.
It is helpful for beginners and experienced persons.
Spring Framework
Spring is a lightweight framework. It can be thought of as a framework
of frameworks because it provides support to various frameworks such
as Struts, Hibernate, Tapestry, EJB, JSF, etc. The framework, in
broader sense, can be defined as a structure where we find solution of
the various technical problems.
The Spring framework comprises several modules such as IOC, AOP,
DAO, Context, ORM, WEB MVC etc. We will learn these modules in next
page. Let's understand the IOC and Dependency Injection first.
Inversion Of Control (IOC) and Dependency
Injection
These are the design patterns that are used to remove dependency
from the programming code. They make the code easier to test and
maintain. Let's understand this with the following code:
1. class Employee{
2. Address address;
ADVANCED JAVA
3. Employee(){
4. address=new Address();
5. }
6. }
In such case, there is dependency between the Employee and Address
(tight coupling). In the Inversion of Control scenario, we do this
something like this:
1. class Employee{
2. Address address;
3. Employee(Address address){
4. this.address=address;
5. }
6. }
Thus, IOC makes the code loosely coupled. In such case, there is no
need to modify the code if our logic is moved to new environment.
In Spring framework, IOC container is responsible to inject the
dependency. We provide metadata to the IOC container either by XML
file or annotation.
Advantage of Dependency Injection
o makes the code loosely coupled so easy to maintain
o makes the code easy to test
Advantages of Spring Framework
There are many advantages of Spring Framework. They are as follows:
ADVANCED JAVA
1) Predefined Templates
Spring framework provides templates for JDBC, Hibernate, JPA etc.
technologies. So there is no need to write too much code. It hides the
basic steps of these technologies.
Let's take the example of JdbcTemplate, you don't need to write the
code for exception handling, creating connection, creating statement,
committing transaction, closing connection etc. You need to write the
code of executing query only. Thus, it save a lot of JDBC code.
2) Loose Coupling
The Spring applications are loosely coupled because of dependency
injection.
3) Easy to test
The Dependency Injection makes easier to test the application. The
EJB or Struts application require server to run the application but
Spring framework doesn't require server.
4) Lightweight
Spring framework is lightweight because of its POJO implementation.
The Spring Framework doesn't force the programmer to inherit any
class or implement any interface. That is why it is said non-invasive.
5) Fast Development
The Dependency Injection feature of Spring Framework and it support
to various frameworks makes the easy development of JavaEE
application.
6) Powerful abstraction
It provides powerful abstraction to JavaEE specifications such
as JMS, JDBC, JPA and JTA.
7) Declarative support
It provides declarative support for caching, validation, transactions and
formatting.
ADVANCED JAVA
Spring Modules
The Spring framework comprises of many modules such as core,
beans, context, expression language, AOP, Aspects, Instrumentation,
JDBC, ORM, OXM, JMS, Transaction, Web, Servlet, Struts etc. These
modules are grouped into Test, Core Container, AOP, Aspects,
Instrumentation, Data Access / Integration, Web (MVC / Remoting) as
displayed in the following diagram.
Test
This layer provides support of testing with Junit and TestNG.
ADVANCED JAVA
Spring Core Container
The Spring Core container contains core, beans, context and
expression language (EL) modules.
Core and Beans
These modules provide IOC and Dependency Injection features.
Context
This module supports internationalization (I18N), EJB, JMS, Basic
Remoting.
Expression Language
It is an extension to the EL defined in JSP. It provides support to
setting and getting property values, method invocation, accessing
collections and indexers, named variables, logical and arithmetic
operators, retrieval of objects by name etc.
AOP, Aspects and Instrumentation
These modules support aspect oriented programming implementation
where you can use Advices, Pointcuts etc. to decouple the code.
The aspects module provides support to integration with AspectJ.
The instrumentation module provides support to class instrumentation
and classloader implementations.
Data Access / Integration
This group comprises of JDBC, ORM, OXM, JMS and Transaction
modules. These modules basically provide support to interact with the
database.
Web
This group comprises of Web, Web-Servlet, Web-Struts and Web-
Portlet. These modules provide support to create web application.
ADVANCED JAVA
Spring Example
Here, we are going to learn the simple steps to create the first spring
application. To run this application, we are not using any IDE. We are
simply using the command prompt. Let’s see the simple steps to
create the spring application
Create the class
Create the xml file to provide the values
Create the test class
Load the spring jar files
Run the test class
Spring with IDE
spring application in Myeclipse
Creating spring application in myeclipse IDE is simple. You
don’t need to be worried about the jar files required for
spring application because myeclipse IDE takes care of it.
Let’s see the simple steps to create the spring application in
myeclipse IDE.
Create the java project
Add spring capabilities
Create the class
Create the xml file to provide the values
Create the test class
Steps to create spring application in Myeclipse IDE
Let’s see the 5 steps to create the first spring application
using myeclipse IDE.
ADVANCED JAVA
1)Create the Java Project
Go to File menu – New – project – Java Project. Write the
project name e.g. firstspring – Finish. Now the java project
is created.
2)Add spring capabilities
Go to Myeclipse menu – Project Capabilities – Add spring
capabilities – Finish. Now the spring jar files will be added.
For the simple application we need only core library i.e.
selected by default.
3)Create Java class
In such case, we are simply creating the Student class have
name property. The name of the student will be provided by
the xml file. It is just a simple example not the actual use of
spring. We will see the actual use in Dependency Injection
chapter. To create the java class, Right click on src – New –
class – Write the class name e.g. Student – finish. Write the
following code:
Package com.javatpoint;
Public class Student {
Private String name;
Public String getName() {
Return name;
Public void setName(String name) {
ADVANCED JAVA
This.name = name;
Public void displayInfo(){
System.out.println(“Hello: “+name);
This is simple bean class, containing only one property name
with its getters and setters method. This class contains one
extra method named displayInfo() that prints the student
name by the hello message.
4)Create the xml file
In case of myeclipse IDE, you don’t need to create the xml
file as myeclipse does this for yourselves. Open the
applicationContext.xml file, and write the following code:
<?xml version=”1.0” encoding=”UTF-8”?>
<beans
Xmlns=http://www.springframework.org/schema/beans
Xmlns:xsi=http://www.w3.org/2001/XMLSchema-
instance
Xmlns:p=http://www.springframework.org/schema/p
Xsi:schemaLocation=”http://www.springframework.org/sche
ma/beans
ADVANCED JAVA
http://www.springframework.org/schema/beans/spring-
beans-3.0.xsd”>
<bean id=”studentbean” class=”com.javatpoint.Student”>
<property name=”name” value=”Vimal
Jaiswal”></property>
</bean>
</beans>
The bean element is used to define the bean for the given
class. The property subelement of bean specifies the
property of the Student class named name. The value
specified in the property element will be set in the Student
class object by the IOC container.
5)Create the test class
Create the java class e.g. Test. Here we are getting the
object of Student class from the IOC container using the
getBean() method of BeanFactory. Let’s see the code of test
class.
Package com.javatpoint;
ADVANCED JAVA
Import org.springframework.beans.factory.BeanFactory;
Import
org.springframework.beans.factory.xml.XmlBeanFactory;
Import org.springframework.core.io.ClassPathResource;
Import org.springframework.core.io.Resource;
Public class Test {
Public static void main(String[] args) {
Resource resource=new
ClassPathResource(“applicationContext.xml”);
BeanFactory factory=new XmlBeanFactory(resource);
Student
student=(Student)factory.getBean(“studentbean”);
Student.displayInfo();
The Resource object represents the information of
applicationContext.xml file. The Resource is the interface
and the ClassPathResource is the implementation class of
the Reource interface. The BeanFactory is responsible to
return the bean. The XmlBeanFactory is the implementation
class of the BeanFactory. There are many methods in the
ADVANCED JAVA
BeanFactory interface. One method is getBean(), which
returns the object of the associated class.
Now run the Test class. You will get the output Hello: Vimal
Jaiswal.
spring application in Eclipse IDE
Here, we are going to create a simple application of spring
framework using eclipse IDE. Let’s see the simple steps to
create the spring application in Eclipse IDE.
Create the java project
Add spring jar files
Create the class
Create the xml file to provide the values
Create the test class
Steps to create spring application in Eclipse IDE
Let’s see the 5 steps to create the first spring application
using eclipse IDE.
1)Create the Java Project
Go to File menu – New – project – Java Project. Write the
project name e.g. firstspring – Finish. Now the java project
is created.
2)Add spring jar files
There are mainly three jar files required to run this
application.
ADVANCED JAVA
Org.springframework.core-3.0.1.RELEASE-A
Com.springsource.org.apache.commons.logging-1.1.1
Org.springframework.beans-3.0.1.RELEASE-A
For the future use, You can download the required jar files
for spring core application.
Download the core jar files for spring
Download the all jar files for spring including aop, mvc, j2ee,
remoting, oxm, etc.
To run this example, you need to load only spring core jar
files.
To load the jar files in eclipse IDE, Right click on your project
– Build Path – Add external archives – select all the required
jar files – finish..
3)Create Java class
In such case, we are simply creating the Student class have
name property. The name of the student will be provided by
the xml file. It is just a simple example not the actual use of
spring. We will see the actual use in Dependency Injection
chapter. To create the java class, Right click on src – New –
class – Write the class name e.g. Student – finish. Write the
following code:
Package com.javatpoint;
Public class Student {
Private String name;
ADVANCED JAVA
Public String getName() {
Return name;
Public void setName(String name) {
This.name = name;
Public void displayInfo(){
System.out.println(“Hello: “+name);
This is simple bean class, containing only one property name
with its getters and setters method. This class contains one
extra method named displayInfo() that prints the student
name by the hello message.
4)Create the xml file
To create the xml file click on src – new – file – give the file
name such as applicationContext.xml – finish. Open the
applicationContext.xml file, and write the following code:
<?xml version=”1.0” encoding=”UTF-8”?>
<beans
Xmlns=http://www.springframework.org/schema/beans
Xmlns:xsi=http://www.w3.org/2001/XMLSchema-
instance
ADVANCED JAVA
Xmlns:p=http://www.springframework.org/schema/p
Xsi:schemaLocation=”http://www.springframework.org/sche
ma/beans
http://www.springframework.org/schema/beans/spring-
beans-3.0.xsd”>
<bean id=”studentbean” class=”com.javatpoint.Student”>
<property name=”name” value=”Vimal
Jaiswal”></property>
</bean>
</beans>
The bean element is used to define the bean for the given
class. The property subelement of bean specifies the
property of the Student class named name. The value
specified in the property element will be set in the Student
class object by the IOC container.
5)Create the test class
Create the java class e.g. Test. Here we are getting the
object of Student class from the IOC container using the
getBean() method of BeanFactory. Let’s see the code of test
class.
Package com.javatpoint;
Import org.springframework.beans.factory.BeanFactory;
Import
org.springframework.beans.factory.xml.XmlBeanFactory;
Import org.springframework.core.io.ClassPathResource;
ADVANCED JAVA
Import org.springframework.core.io.Resource;
Public class Test {
Public static void main(String[] args) {
Resource resource=new
ClassPathResource(“applicationContext.xml”);
BeanFactory factory=new XmlBeanFactory(resource);
Student
student=(Student)factory.getBean(“studentbean”);
Student.displayInfo();
Now run this class. You will get the output Hello: Vimal
Jaiswal.
Spring Dependency Injection
What is Dependency Injection:
Dependency Injection is the main functionality provided by
Spring IOC(Inversion of Control). The Spring-Core module is
responsible for injecting dependencies through either
Constructor or Setter methods. The design principle of
Inversion of Control emphasizes keeping the Java classes
independent of each other and the container frees them
from object creation and maintenance. These classes,
managed by Spring, must adhere to the standard definition
of Java-Bean. Dependency Injection in Spring also ensures
loose-coupling between the classes.
ADVANCED JAVA
Need for Dependency Injection:
Suppose class One needs the object of class Two to
instantiate or operate a method, then class One is said to be
dependent on class Two. Now though it might appear okay
to depend a module on the other but, in the real world, this
could lead to a lot of problems, including system failure.
Hence such dependencies need to be avoided.
Spring IOC resolves such dependencies with Dependency
Injection, which makes the code easier to test and reuse.
Loose coupling between classes can be possible by defining
interfaces for common functionality and the injector will
instantiate the objects of required implementation. The task
of instantiating objects is done by the container according to
the configurations specified by the developer.
Types of Spring Dependency Injection:
There are two types of Spring Dependency Injection. They
are:
Setter Dependency Injection (SDI): This is the simpler
of the two DI methods. In this, the DI will be injected with
the help of setter and/or getter methods. Now to set the DI
as SDI in the bean, it is done through the bean-configuration
file For this, the property to be set with the SDI is declared
under the <property> tag in the bean-config file.
Example: Let us say there is class GFG that uses SDI and
sets the property geeks. The code for it is given below.
Package com.geeksforgeeks.org;
Import com.geeksforgeeks.org.IGeek;
ADVANCED JAVA
Public class GFG {
// The object of the interface IGeek
IGeek geek;
// Setter method for property geek
Public void setGeek(IGeek geek)
{ This.geek = geek;
Constructor Dependency Injection (CDI): In this, the DI
will be injected with the help of constructors. Now to set the
DI as CDI in bean, it is done through the bean-configuration
file For this, the property to be set with the CDI is declared
under the <constructor-arg> tag in the bean-config file.
Example: Let us take the same example as of SDI
Package com.geeksforgeeks.org;
Import com.geeksforgeeks.org.IGeek;
Public class GFG {
// The object of the interface IGeek
IGeek geek;
// Constructor to set the CDI
GFG(IGeek geek)
{
ADVANCED JAVA
This.geek = geek;
Example of DI:
Public class Vehicle {
IEngine engine;
Tyres tyre;
Public Tyres getTyre()
Return tyre;
Public void setTyre(Tyres tyre)
System.out.println(“tyre instantiated via setter”);
This.tyre = tyre;
}
ADVANCED JAVA
Public Vehicle(IEngine engine, Tyres tyre)
System.out.println(“instantiated via constructor”);
This.engine = engine;
This.tyre = tyre;
Public Vehicle() {}
Public IEngine getEngine()
Return engine;
Public void setEngine(IEngine engine)
System.out.println(“instantiated via setter”);
This.engine = engine;
@Override
Public String toString()
Return engine + “ “ + tyre;
ADVANCED JAVA
}
Public static void main(String a[])
ApplicationContext rootctx
= new ClassPathXmlApplicationContext(
“springContext.xml”);
// Instantiating the obj1 via Constructor DI
Vehicle obj1
= (Vehicle)rootctx
.getBean(“InjectwithConstructor”);
// Instantiating the obj1 via Setter DI
Vehicle obj2
= (Vehicle)rootctx
.getBean(“InjectwithSetter”);
System.out.println(obj1);
System.out.println(obj2);
System.out.println(obj1 == obj2);
}
ADVANCED JAVA
Aspect Oriented Programming and AOP in
Spring Framework
Aspect oriented programming(AOP) as the name suggests uses aspects in
programming. It can be defined as the breaking of code into different modules, also
known as modularisation, where the aspect is the key unit of modularity. Aspects
enable the implementation of crosscutting concerns such as- transaction, logging not
central to business logic without cluttering the code core to its functionality. It does
so by adding additional behaviour that is the advice to the existing code. For
example- Security is a crosscutting concern, in many methods in an application
security rules can be applied, therefore repeating the code at every method, define
the functionality in a common class and control were to apply that functionality in
the whole application.
Dominant Frameworks in AOP:
AOP includes programming methods and frameworks on which modularisation of
code is supported and implemented. Let’s have a look at the three dominant
frameworks in AOP:
7. AspectJ: It is an extension for Java programming created at PARC research
centre. It uses Java like syntax and included IDE integrations for displaying
crosscutting structure. It has its own compiler and weaver, on using it enables
the use of full AspectJ language.
8. JBoss: It is an open source Java application server developed by JBoss, used for
Java development.
9. Spring: It uses XML based configuration for implementing AOP, also it uses
annotations which are interpreted by using a library supplied by AspectJ for
parsing and matching.
ADVANCED JAVA
Currently, AspectJ libraries with Spring framework are dominant in the market,
therefore let’s have an understanding of how Aspect-oriented programming works
with Spring.
How Aspect-Oriented Programming works with Spring:
One may think that invoking a method will automatically implement cross-cutting
concerns but that is not the case. Just invocation of the method does not invoke the
advice(the job which is meant to be done). Spring uses proxy based mechanism i.e.
it creates a proxy Object which will wrap around the original object and will take up
the advice which is relevant to the method call. Proxy objects can be created either
manually through proxy factory bean or through auto proxy configuration in the
XML file and get destroyed when the execution completes. Proxy objects are used to
enrich the Original behaviour of the real object.
Common terminologies in AOP:
7. Aspect: The class which implements the JEE application cross-cutting
concerns(transaction, logger etc) is known as the aspect. It can be normal class
configured through XML configuration or through regular classes annotated with
@Aspect.
8. Weaving: The process of linking Aspects with an Advised Object. It can be done
at load time, compile time or at runtime time. Spring AOP does weaving at
runtime.
9. ant to be done by an Aspect or it can be defined as the action taken by the
Aspect at a particular point. There are five types of Advice namely: Before, After,
Around, AfterThrowing and AfterReturning. Let’s have a brief discussion about
all the five types.
Types of Advices:
10. Before: Runs before the advised method is invoked. It is denoted
by @Before annotation.
11. After: Runs after the advised method completes regardless of the outcome,
whether successful or not. It is denoted by @After annotation.
ADVANCED JAVA
12. AfterReturning: Runs after the advised method successfully completes ie
without any runtime exceptions. It is denoted by @AfterReturning annotation.
13. Around: This is the strongest advice among all the advice since it wraps around
and runs before and after the advised method. This type of advice is used where
we need frequent access to a method or database like- caching. It is denoted
by @Around annotation.
14. AfterThrowing: Runs after the advised method throws a Runtime Exception. It is
denoted by @AfterThrowing annotation.
Spring Jdbc Template
Spring JdbcTemplate is a powerful mechanism to connect to the
database and execute SQL queries. It internally uses JDBC api, but
eliminates a lot of problems of JDBC API.
Problems of JDBC API
The problems of JDBC API are as follows:
We need to write a lot of code before and after executing the query, such as creating
connection, statement, closing resultset, connection etc.
We need to perform exception handling code on the database logic.
We need to handle transaction.
Repetition of all these codes from one to another database logic is a timeconsuming task.
Advantage of Spring JdbcTemplate
Spring JdbcTemplate eliminates all the above mentioned problems of JDBC API. It provides
you methods to write the queries directly, so it saves a lot of work and time.
Spring Jdbc Approaches
Spring framework provides following approaches for JDBC database access:
JdbcTemplate
NamedParameterJdbcTemplate
No. Method Description
1) public int update(String is used to insert,
query) update and delete
ADVANCED JAVA records.
2) public int update(String is used to insert,
query,Object… args) update and delete
SimpleJdbcTem
records using
plate
PreparedStatement
using given
SimpleJdbcInser
arguments.
3) public void execute(String is used to execute t and
query) DDL query. SimpleJdbcCall
4) public T execute(String sql, executes the query
PreparedStatementCallback by using JdbcTemplate
action) PreparedStatement class
It is the central
class in the
Spring JDBC
support classes.
It takes care of
creation and
release of resources such as creating and closing of connection object etc. So it will not
lead to any problem if you forget to close the connection.
It handles the exception and provides the informative exception messages by the help of
excepion classes defined in the org.springframework.dao package.
We can perform all the database operations by the help of JdbcTemplate class such as
insertion, updation, deletion and retrieval of the data from the database.
Let’s see the methods of spring JdbcTemplate class.
ADVANCED JAVA
callback.
5) public T query(String sql, is used to fetch
ResultSetExtractor rse) records using
ResultSetExtractor.
6) public List query(String sql, is used to fetch
RowMapper rse) records using
RowMapper.
Spring with ORM Frameworks
Spring provides API to easily integrate Spring with ORM frameworks such as Hibernate,
JPA(Java Persistence API), JDO(Java Data Objects), Oracle Toplink and iBATIS.
Advantage of ORM Frameworks with Spring
There are a lot of advantage of Spring framework in respect to ORM frameworks. There are
as follows:
Less coding is required: By the help of Spring framework, you don’t need to write extra
codes before and after the actual database logic such as getting the connection, starting
transaction, commiting transaction, closing connection etc.
Easy to test: Spring’s IoC approach makes it easy to test the application.
Better exception handling: Spring framework provides its own API for exception handling
with ORM framework.
Integrated transaction management: By the help of Spring framework, we can wrap our
mapping code with an explicit template wrapper class or AOP style method interceptor.