Module V (Spring) : 1. Dependency Injection or Inversion of Control (IOC)
Module V (Spring) : 1. Dependency Injection or Inversion of Control (IOC)
7. View Helper:
Spring framework provides a large number of custom JSP tags as well as velocity macros which
assist in the separation of code from the presentation (i.e., views).
8. Template method:
Spring framework provides a number of templates to kick start work and complete that piece
of work as the best programming practice such as opening and closing connection for JDBC or
JMS, etc. E.g., JdbcTemplate, JmsTemplate, and JpaTemplate.
The framework, in broader sense, can be defined as a structure where we find solution
of the various technical problems.
Spring Framework is the most popular application development framework of Java.
The main feature of the Spring Framework is dependency Injection or Inversion
of Control (IoC). With the help of Spring Framework, we can develop a loosely
coupled application.
Spring is the most popular application development framework for enterprise Java.
Millions of developers around the world use Spring Framework to create high
performing, easily testable, and reusable code.
Spring framework is an open source Java platform. It was initially written by Rod
Johnson and was first released under the Apache 2.0 license in June 2003.
Spring is lightweight when it comes to size and transparency. The basic version of
Spring framework is around 2MB.
The core features of the Spring Framework can be used in developing any Java
application, but there are extensions for building web applications on top of the Java
EE platform. Spring framework targets to make J2EE development easier to use and
promotes good programming practices by enabling a POJO-based programming
model.
Spring Boot:
The primary feature of the Spring Framework is dependency injection. The primary
feature of Spring Boot is Autoconfiguration. It automatically configures the classes
based on the requirement.
In Spring the developer writes a lot of code (boilerplate code) to do the minimal
task. Spring Boot reduces boilerplate code.
It helps to make things simpler It helps to create a stand-alone application with less
by allowing us to develop configuration.
loosely coupled applications.
It does not provide support for It offers several plugins for working with an embedded
an in-memory database. and in-memory database such as H2.
Developers manually define Spring Boot comes with the concept of starter in pom.xml
dependencies for the Spring file that internally takes care of downloading the
project in pom.xml. dependencies JARs based on Spring Boot Requirement.
IoC Containers
The Spring container is at the core of the Spring Framework. The container will create
the objects, wire them together, configure them, and manage their complete life cycle
from creation till destruction. The Spring container uses DI to manage the components
that make up an application. These objects are called Spring Beans.
The container gets its instructions on what objects to instantiate, configure, and
assemble by reading the configuration metadata provided. The configuration
metadata can be represented either by XML, Java annotations, or Java code. The
following diagram represents a high-level view of how Spring works. The Spring IoC
container makes use of Java POJO classes and configuration metadata to produce a
fully configured and executable system or application.
Spring provides the following two distinct types of containers.
This is the simplest container providing the basic support for DI and is defined by the
org.springframework.beans.factory.BeanFactory interface. The BeanFactory and
related interfaces, such as BeanFactoryAware, InitializingBean, DisposableBean, are
still present in Spring for the purpose of backward compatibility with a large number
of third-party frameworks that integrate with Spring.
This container adds more enterprise-specific functionality such as the ability to resolve
textual messages from a properties file and the ability to publish application events
to interested event listeners. This container is defined by the
org.springframework.context.ApplicationContext interface.
The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity
is the aspect. DI helps you decouple your application objects from each other, while
AOP helps you decouple cross-cutting concerns from the objects that they affect.
In other words…..
The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity
is the aspect. Dependency Injection helps you decouple your application objects from
each other and AOP helps you decouple cross-cutting concerns from the objects that
they affect. AOP is like triggers in programming languages such as Perl, .NET, Java,
and others.
In other words…..
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.
Spring Architecture
Spring could potentially be a one-stop shop for all your enterprise applications. However,
Spring is modular, allowing you to pick and choose which modules are applicable to you,
without having to bring in the rest. The following section provides details about all the modules
available in Spring Framework.
The Spring Framework provides about 20 modules which can be used based on an application
requirement.
Core Container
The Core Container consists of the Core, Beans, Context, and Expression Language modules
the details of which are as follows −
• The Core module provides the fundamental parts of the framework, including the IoC
and Dependency Injection features.
• The Bean module provides BeanFactory, which is a sophisticated implementation of
the factory pattern.
• The Context module builds on the solid base provided by the Core and Beans
modules and it is a medium to access any objects defined and configured. The
ApplicationContext interface is the focal point of the Context module.
• The SpEL module provides a powerful expression language for querying and
manipulating an object graph at runtime.
Data Access/Integration
The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction
modules whose detail is as follows −
• The JDBC module provides a JDBC-abstraction layer that removes the need for
tedious JDBC related coding.
• The ORM module provides integration layers for popular object-relational mapping
APIs, including JPA, JDO, Hibernate, and iBatis.
• The OXM module provides an abstraction layer that supports Object/XML mapping
implementations for JAXB, Castor, XMLBeans, JiBX and XStream.
• The Java Messaging Service JMS module contains features for producing and
consuming messages.
• The Transaction module supports programmatic and declarative transaction
management for classes that implement special interfaces and for all your POJOs.
Web
The Web layer consists of the Web, Web-MVC, Web-Socket, and Web-Portlet modules the
details of which are as follows −
• The Web module provides basic web-oriented integration features such as multipart
file-upload functionality and the initialization of the IoC container using servlet
listeners and a web-oriented application context.
• The Web-MVC module contains Spring's Model-View-Controller (MVC)
implementation for web applications.
• The Web-Socket module provides support for WebSocket-based, two-way
communication between the client and the server in web applications.
• The Web-Portlet module provides the MVC implementation to be used in a portlet
environment and mirrors the functionality of Web-Servlet module.
Miscellaneous
There are few other important modules like AOP, Aspects, Instrumentation, Web and Test
modules the details of which are as follows −
Consider you have an application which has a text editor component and you want to provide
a spell check. Your standard code would look something like this −
public TextEditor() {
spellChecker = new SpellChecker();
}
}
What we've done here is, create a dependency between the TextEditor and the SpellChecker.
In an inversion of control scenario, we would instead do something like this −
Here, the TextEditor should not worry about SpellChecker implementation. The
SpellChecker will be implemented independently and will be provided to the TextEditor at
the time of TextEditor instantiation. This entire procedure is controlled by the Spring
Framework.
Here, we have removed total control from the TextEditor and kept it somewhere else (i.e.
XML configuration file) and the dependency (i.e. class SpellChecker) is being injected into
the class TextEditor through a Class Constructor. Thus the flow of control has been
"inverted" by Dependency Injection (DI) because you have effectively delegated
dependances to some external system.
The second method of injecting dependency is through Setter Methods of the TextEditor
class where we will create a SpellChecker instance. This instance will be used to call setter
methods to initialize TextEditor's properties.
The code is cleaner with the DI principle and decoupling is more effective when objects are
provided with their dependencies. The object does not look up its dependencies and does not
know the location or class of the dependencies, rather everything is taken care by the Spring
Framework.
Spring JDBC
While working with the database using plain old JDBC, it becomes cumbersome to
write unnecessary code to handle exceptions, opening and closing database
connections, etc. However, Spring JDBC Framework takes care of all the low-level
details starting from opening the connection, prepare and execute the SQL statement,
process exceptions, handle transactions and finally close the connection.
So what you have to do is just define the connection parameters and specify the SQL
statement to be executed and do the required work for each iteration while fetching
data from the database.
Spring JDBC provides several approaches and correspondingly different classes to interface
with the database. I'm going to take classic and the most popular approach which makes use
of JdbcTemplate class of the framework. This is the central framework class that manages
all the database communication and exception handling.
JdbcTemplate Class
The JDBC Template class executes SQL queries, updates statements, stores procedure calls,
performs iteration over ResultSets, and extracts returned parameter values. It also catches
JDBC exceptions and translates them to the generic, more informative, exception hierarchy
defined in the org.springframework.dao package.
Instances of the JdbcTemplate class are threadsafe once configured. So you can configure a
single instance of a JdbcTemplate and then safely inject this shared reference into multiple
DAOs.
A common practice when using the JDBC Template class is to configure a DataSource in
your Spring configuration file, and then dependency-inject that shared DataSource bean into
your DAO classes, and the JdbcTemplate is created in the setter for the DataSource.
Now we need to supply a DataSource to the JDBC Template so it can configure itself to get
database access. You can configure the DataSource in the XML file with a piece of code as
shown in the following code snippet −
<bean id = "dataSource"
class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
<property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/>
<property name = "username" value = "root"/>
<property name = "password" value = "password"/>
</bean>
The DAO support in Spring makes it easy to work with data access technologies like JDBC,
Hibernate, JPA, or JDO in a consistent way.
return student;
}
}
return student;
}
}
String SQL = "insert into Student (name, age) values (?, ?)";
jdbcTemplateObject.update( SQL, new Object[]{"Zara", 11} );
jdbcTemplateObject.execute( SQL );