0% found this document useful (0 votes)
14 views

Spring 2.0

Uploaded by

krish40041
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Spring 2.0

Uploaded by

krish40041
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 127

Spring Framework

Spring Framework Introduction

❖ Spring Framework is a Java platform based framework , that


provides comprehensive infrastructure support for developing Java
applications.
❖ Spring handles the infrastructure so developers can focus on
application development/Business logic .
❖ The Spring Framework is divided into modules. Applications can
choose which modules they need. At the heart are the modules of the
core container, including a configuration model and a dependency
injection mechanism.
❖ Spring came into being in 2003 as a response to the complexity of
the early J2EE specifications.
❖ Beyond the Spring Framework, there are other projects, such as
Spring Boot, Spring Security, Spring Data, Spring Cloud, Spring Batch,
among others.
❖ Guiding principles of the Spring Framework
■ · Provide choice at every level
■ · Accommodate diverse perspectives
■ · Maintain strong backward compatibility
■ · Care about API design
■ · Set high standards for code quality
❖ As mentioned above Spring is a vast framework, Some important
modules given below
★· Spring Core
★· Spring AOP
★· Spring JDBC
★· Spring Transaction
★· Spring ORM
★· Spring MVC

❖ All the modules of Spring are independent of each other except


Spring Core. As Spring core is the base module, so in all modules we
have to use Spring Core.
❖ The Major features of Spring framework are
■ · Inversion Of Control
■ · Dependency Injection.

Core Container
❖ The Core Container consists of the Core, Beans, Context, and
Expression Language modules.
❖ The Core and Beans modules provide the fundamental parts of the
framework, including the IoC and Dependency Injection features.
The BeanFactory is a sophisticated implementation of the factory
❖ It removes the need for programmatic singletons and allows you to
decouple the configuration and specification of dependencies from
your actual program logic.
❖ The Context module builds on the solid base provided by the Core
and Beans modules: it is a means to access objects in a
framework-style manner that is similar to a JNDI registry.
❖ The Context module inherits its features from the Beans module and
adds support for internationalization (using, for example,resource
bundles), event-propagation, resource-loading, and the transparent
creation of contexts.
❖ for example, a servlet container. The Context module also supports
Java EE features such as EJB, JMX ,and basic remoting. The
ApplicationContext interface is the focal point of the Context
module.
❖ The Expression Language module provides a powerful expression
language for querying and manipulating an object graph at runtime.
It is an extension of the unified expression language (unified EL) as
specified in the JSP 2.1 specification. The language supports setting
and getting property values.
❖ property assignment, method invocation, accessing the context of
arrays, collections and indexers.
❖ logical and arithmetic operators, named variables, and retrieval of
objects by name from Spring’s IoC container. It also supports list
projection and selection as well as common list aggregations.
Data Access/Integration

❖ The Data Access/Integration layer consists of the JDBC, ORM,


OXM, JMS and Transaction modules.
❖ The JDBC module provides a JDBC-abstraction layer that
removes the need to do tedious JDBC coding and parsing of
database-vendor specific error codes.
❖ The ORM module provides integration layers for popular
object-relational mapping APIs, including JPA, JDO, and
Hibernate.
❖ Using the ORM package you can use all of these O/R-mapping
frameworks in combination with all of the other features Spring
offers, such as the simple declarative transaction management
feature mentioned previously.
❖ 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 (plain old Java
objects).

Web

❖ The Web layer consists of the Web, Web-Servlet, WebSocket


and Web-Portlet modules.
❖ Spring’s 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.
❖ It also contains the web-related parts of Spring’s remoting
support.
❖ The Web-Servlet module contains Spring’s
model-view-controller (MVC) implementation for web
applications. Spring’s MVC framework provides a clean
separation between domain model code and web forms, and
integrates with all the other features of the Spring Framework.
❖ The Web-Portlet module provides the MVC implementation to
be used in a portlet environment and mirrors the functionality
of the Web-Servlet module.

AOP and Instrumentation

❖ Spring’s AOP module provides an AOP Alliance-compliant


aspect-oriented programming implementation allowing you to
define.
❖ For example, method-interceptors and pointcuts to cleanly
decouple code that implements functionality that should be
separated.
❖ Using source-level metadata functionality, you can also
incorporate behavioral information into your code, in a manner
similar to that of .NET attributes.
❖ The separate Aspects module provides integration with
AspectJ.
❖ The Instrumentation module provides class instrumentation
support and classloader implementations to be used in certain
application servers.
Typical full-fledged Spring web application.

Dependency Management and Naming Conventions

Dependency management and dependency injection are different things.


To get those nice features of Spring into your application (like dependency
injection) you need to assemble all the libraries needed (jar files) and get
them onto your classpath at runtime, and possibly at compile time. These
dependencies are not virtual components that are injected, but physical
resources in a file system (typically).
The process of dependency management involves locating those resources,
storing them and adding them to classpaths. Dependencies can be direct
(e.g. my application depends on Spring at runtime), or indirect

(e.g. my application depends on commons-dbcp which depends on


commons-pool).

➔ The indirect dependencies are also known as "transitive" and it is


those dependencies that are hardest to identify and manage.
➔ If you are going to use Spring you need to get a copy of the jar
libraries that comprise the pieces of Spring that you need. To make
this easier Spring is packaged as a set of modules that separate the
dependencies as much as possible, so for example if you don’t want
to write a web application you
➔ don’t need the spring-web modules. To refer to Spring library
modules in this guide we use a shorthand naming convention
spring-* or spring-*.jar, where * represents the short name for the
module

(e.g. spring-core, spring-webmvc, spring-jms, etc.). The actual jar file name
that you use is normally the module name concatenated with the version
number (e.g. spring-core-5.0.9.RELEASE.jar).

Link :
https://repo.spring.io/release/org/springframework/spring/5.2.0.RELEASE/

Each release of the Spring Framework will publish artifacts to the following
places:

• Maven Central, which is the default repository that Maven queries, and
does not require any special configuration to use. Many of the common
libraries that Spring depends on also are available from Maven Central and
a large section of the Spring community uses Maven for dependency
management, so this is convenient for them. The names of the jars here are
in the form spring-*-

<version>.jar and the Maven groupId is org.springframework.

• In a public Maven repository hosted specifically for Spring. In addition to


the final GA releases, this repository also hosts development snapshots and
milestones. The jar file names are in the same form as Maven Central, so
this is a useful place to get development versions of Spring to use with
other libraries deployed in Maven Central. This repository also contains a
bundle distribution zip file that contains all Spring jars bundled together
for easy download.

So the first thing you need to decide is how to manage your dependencies:
we generally recommend the use of an automated system like Maven,
Gradle or Ivy, but you can also do it manually by downloading all the jars
❖ Inversion of Control (IoC) is a design principle (although, some
people refer to it as a pattern). As the name suggests, it is used to
invert different kinds of controls in object-oriented design to achieve
loose coupling.

❖ The core of spring framework is it’s bean factory and mechanisms to


create and manage such beans inside Spring container. The beans in
the spring container can be created in five scopes .
❖ How can containers manage beans ?
What are the advantages of Spring framework?
❖ Lightweight: Spring is lightweight. The basic version of the Spring
framework is around 2MB.
❖ Dependency Injection/Inversion of Control (IoC): This helps to
achieve loose coupling by wiring of independent components/objects
❖ Spring Container: contains and manages the lifecycle of the
application objects
❖ Transaction Management: Spring supports the transaction
management i.e. JDBC operation, File uploading, Exception Handling
etc either by spring annotation or bean configuration.
❖ Spring MVC: Spring MVC can be used to create Web application as
well as restful web services which is capable of returning XML or
JSON response
❖ Exception Handling: Spring provides a convenient API to translate
technology specific exceptions (thrown by JDBC, Hibernate etc) into
consistent unchecked exceptions
❖ Aspect Oriented Programming(AOP): AOP breaks the program logic
into distinct parts (called concerns). It is used to increase modularity
by cross-cutting concerns. A cross-cutting concern is a concern that
can affect the whole application and should be centralized in one
location in code as possible, such as transaction management,
authentication, logging, security etc

❖ What is Spring Bean?


❖ Any normal Java class that is initialized by a Spring IoC
container is called Spring Bean. We use spring application
context to get Spring Bean instances. Spring IoC Container
manages the lifecycle of Spring Bean scope and injects any
required dependencies in the bean.
❖ Different scopes of Spring bean ?
❖ When we declare <bean>, we can specify the scope of the bean
to inform the IoC container about the creation of the bean and
how long it will survive.
❖ For any java application there are two different scopes called
singleton and prototype.
❖ There are three different scopes i.e. request, session and
global-session specially for spring based java Web applications.
❖ Singleton is the default scope of any bean. This means a single
instance of the bean will get created per IoC container. Hence
the Singleton beans are not thread safe.
❖ In prototype scope a new instance will get created every time
the bean is requested.
❖ In request scope, a bean is defined to an HTTP request. This
scope is valid only in a web-aware spring ApplicationContext.
❖ In session scope, a bean is defined to an HTTP session. This
scope is valid only in a web-aware spring ApplicationContext.
❖ In global-session scope, a bean is defined to a global HTTP
session. This scope is valid only in a web-aware spring
ApplicationContext.
❖ To set the scope of the spring bean, we can use the scope
attribute in <bean> tag. @scope is used in annotation based DI.

Spring IoC Container


❖ 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 dependency injection (DI) to
manage the components that make up an application.
There are two different types of containers
BeanFactory container: This is the heart of the Spring
container. org.springframework.beans.factory.BeanFactory is
an interface and acts as a IoC container which instantiates,
configures, and manages a number of beans.
❖ ApplicationContext container:
org.springframework.context.ApplicationContext
interface also acts as the IoC container but the
ApplicationContext interface is built on top of the
BeanFactory interface to provides some extra
functionality than BeanFactory such as simple
integration with Spring’s AOP, message resource handling
(for I18N), event propagation, application layer specific
context (e.g. WebApplicationContext) for web
application. So it is better to use ApplicationContext than
BeanFactory.

@Autowired
❖ For annotation based dependency injection, @Autowired
annotation is used. The classes marked with
@Component/@Service/@Repository etc can be injected
to the property which is marked with @Autowired

@Autowired is applied to
❖ field: for the field-based dependency injection
❖ setter for the setter dependency injection. Same as
field-based dependency injection.
❖ constructor for constructor-based dependency injection.

Difference between constructor based and setter based DI ?


❖ Injection of dependencies can be optional or mandatory.
For mandatory injection we use constructor based DI. While for
the optional dependencies we can use setter based DI. However,
we can mark a setter based DI with @Required annotation.
❖ In case of cyclic dependency, constructor based DI won’t
be able to inject but setter based DI would be able to inject
❖ If more number of parameters to be injected then it is
advisable to use constructor based DI.

Difference between context:annotation-config and


context:component-scan ?
❖ context:annotation-config is used to activate annotations in beans
already registered in the application context .
❖ context:component-scan can also do what context:annotation-config
does but also scans packages to find and register beans within the
application context.

Difference between @Component, @Controller, @Repository & @Service


annotations ?
If a class is marked with
@Component/@Controller/@Service/@Repository annotation then the
spring DI container can identify the class during component scan
mechanism. However, it is a good idea to use @Service for service layer
classes, and @Controller should be used in spring mvc web controller.
@Repository is used to import DAOs into DI containers. Also any
unchecked exception will get translated into Spring DataAccessException.
Transaction management in Spring
Database transaction is a set of actions treated as the unit of work. Main
principle of a transaction is either commit all actions or rollback
everything in case of failure. While committing data in a transaction, we
need to ensure the transaction agreement/properties called ACID
(Atomicity-Consistency-Isolation-Durability)

❖ Atomicity: All operations in a transaction are considered as a unit of


work. Hence, a transaction will be either committed or roll backed.
❖ Consistency: This ensures that a transaction will bring the database
from one valid state to another valid state by maintaining the
referential integrity of the database
❖ Isolation: Each transaction should be isolated from other
transactions even though they are working on the same set of data.
❖ Durability: This ensures that once a transaction is completed, the
data will be made permanent in the database. The data will not get
lost even after power loss or system crash.
❖ Spring supports both Programmatic and Declarative transaction
management. It also supports Global and Local transactions.

Dependencies and configuration in detail


Straight values (primitives, Strings, and so on)
The value attribute of the <property/> element specifies a property or
constructor argument as a human-readable string representation.
Spring’s conversion service is used to convert these values from
a String to the actual type of the property or argument.
You can also configure a java.util.Properties instance as:

The Spring container converts the text inside the <value/> element into a
java.util.Properties instance by using the JavaBeans PropertyEditor
mechanism. This is a nice shortcut, and is one of
a few places where the Spring team do favor the use of the nested <value/>
element over the value attribute style.

The idref element


The idref element is simply an error-proof way to pass the id (string value -
not a reference) of another
bean in the container to a <constructor-arg/> or <property/> element.
Collections
In the <list/>, <set/>, <map/>, and <props/> elements, you set the
properties and arguments of
the Java Collection types List, Set, Map, and Properties, respectively.
Lazy-initialized beans
➔ By default, ApplicationContext implementations eagerly create and
configure all singleton beans as part of the initialization process.
➔ Generally, this pre-instantiation is desirable, because errors in the
➔ configuration or surrounding environment are discovered
immediately, as opposed to hours or even days later.
➔ When this behavior is not desirable, you can prevent
pre-instantiation of a singleton bean by marking the bean definition
as lazy-initialized.
➔ A lazy-initialized bean tells the IoC container to create a
➔ bean instance when it is first requested, rather than at startup.
➔ In XML, this behavior is controlled by the lazy-init attribute on the
<bean/> element;

➔ When the preceding configuration is consumed by an


ApplicationContext, the bean named lazy is not eagerly
pre-instantiated when the ApplicationContext is starting up,
whereas the not. Lazy bean is eagerly pre-instantiated.
➔ However, when a lazy-initialized bean is a dependency of a
singleton bean that is not lazy-initialized, the
ApplicationContext creates the lazy-initialized bean at startup,
because it must satisfy the singleton’s dependencies.
➔ The lazy-initialized bean is injected into a singleton bean
elsewhere that is not lazy-initialized.

Autowiring collaborators
➔ The Spring container can autowire relationships between
collaborating beans.
➔ You can allow Spring to resolve collaborators (other beans)
automatically for your bean by inspecting the contents of the
ApplicationContext.

Autowiring has the following advantages:


• Autowiring can significantly reduce the need to specify properties or
constructor arguments. (Other mechanisms such as a bean template
discussed elsewhere in this chapter are also valuable in this regard.)
• Autowiring can update a configuration as your objects evolve. For
example, if you need to add a dependency to a class, that dependency can
be satisfied automatically without you needing to modify the
configuration. Thus autowiring can be especially useful during
development, without negating the option of switching to explicit wiring
when the code base becomes more stable.
When using XML-based configuration metadata 10, you specify autowire
mode for a bean definition with the autowire attribute of the <bean/>
element.
The autowiring functionality has different modes. You specify autowiring
per bean and thus can choose which ones to autowire.
❖ No
❖ byName
❖ byType
❖ constructor

PropertyPlaceholderConfigurer
❖ You use the PropertyPlaceholderConfigurer to externalize property
values from a bean definition in a separate file using the standard
Java Properties format.
❖ Doing so enables the person deploying an application to customize
environment-specific properties such as database URLs and
passwords, without the complexity or risk of modifying the main
XML definition file or files for the container.
❖ Consider the following XML-based configuration metadata fragment,
where a DataSource with placeholder values is defined.
❖ The example shows properties configured from an external
Properties file. At runtime, a PropertyPlaceholderConfigurer is
applied to the metadata that will replace some properties of the
DataSource.
❖ The values to replace are specified as placeholders of the form
${property-name} which follows the Ant / log4j / JSP EL style.

❖ Therefore, the string ${jdbc.username} is replaced at runtime with


the values , and the same applies for other placeholder values that
match keys in the properties file.
❖ The PropertyPlaceholderConfigurer checks for placeholders in most
properties and attributes of a bean definition. Furthermore, the
placeholder prefix and suffix can be customized.
<context:property-placeholder
location="classpath:com/foo/jdbc.properties"/>

@Required
The @Required annotation applies to bean property setter methods, as in
the following example:

❖ This annotation simply indicates that the affected bean property


must be populated at configuration time, through an explicit
property value in a bean definition or through autowiring.
❖ The container throws an exception if the affected bean property has
not been populated; this allows for eager and explicit failure,
avoiding NullPointerExceptions or the like later on.
❖ It is still recommended that you put assertions into the bean class
itself, for example, into an init method. Doing so enforces those
required references and values even when you use the class outside of
a container.

@Autowired
As expected, you can apply the @Autowired annotation to "traditional"
setter methods:
❖ You can also apply the annotation to methods with arbitrary names
and/or multiple arguments.
❖ You can apply @Autowired to constructors and fields.

Fine-tuning annotation-based autowiring with qualifiers


Because autowiring by type may lead to multiple candidates, it is often
necessary to have more control over the selection process.
One way to accomplish this is with Spring’s @Qualifier annotation
The @Qualifier annotation can also be specified on individual constructor
arguments or method parameters:

@PostConstruct and @PreDestroy


❖ The CommonAnnotationBeanPostProcessor not only recognizes the
@Resource annotation but also the JSR-250 lifecycle annotations.
Introduced in Spring 2.5, the support for these annotations offers yet
another alternative to those described in initialization callbacks and
destruction callbacks.
❖ Provided that the CommonAnnotationBeanPostProcessor is
registered within the Spring ApplicationContext, a method carrying
one of these annotations is invoked at the same point in the lifecycle
as the corresponding Spring lifecycle interface method or explicitly
declared callback method.
❖ In the example below, the cache will be pre-populated upon
initialization and cleared upon destruction
Automatically detecting classes and registering bean definitions
❖ Spring can automatically detect stereotyped classes and register
corresponding BeanDefinitions with the ApplicationContext.
❖ For example, the following two classes are eligible for such
autodetection:
To autodetect these classes and register the corresponding beans,
you need to include the following element in XML, where the
base-package element is a common parent package for the two
classes. (Alternatively, you can specify
comma/semicolon/space/tab/line feed- separated list that includes
the parent package of each class.)

The use of <context:component-scan> implicitly enables the functionality


of <context:annotation-config>. There is usually no need to include the
<context:annotation-config> element when using
<context:component-scan>.

Naming autodetected components


When a component is autodetected as part of the scanning process, its
bean name is generated by the BeanNameGenerator strategy known to that
scanner. By default, any Spring stereotype annotation (
@Component, @Repository, @Service, and @Controller) that contains a
name value will thereby provide that name to the corresponding bean
definition.
Providing a scope for autodetected components
As with Spring-managed components in general, the default and most
common scope for autodetected components is singleton.
However, sometimes you need other scopes, which Spring 2.5 provides with
a new @Scope annotation. Simply provide the name of the scope within
the annotation:

Java-based container configuration

Basic concepts: @Bean and @Configuration

❖ The central artifacts in Spring’s new Java-configuration support are


@Configuration-annotated classes and @Bean-annotated methods.
❖ The @Bean annotation is used to indicate that a method
instantiates, configures and initializes a new object to be managed by
the Spring IoC container. For those familiar with Spring’s <beans/>
XML configuration the @Bean annotation plays the same role as the
<bean/> element.
❖ You can use @Bean annotated methods with any Spring
@Component, however, they are most often used with
@Configuration beans.

❖ Annotating a class with @Configuration indicates that its primary


purpose is as a source of bean definitions.
❖ Furthermore, @Configuration classes allow inter-bean dependencies
to be defined by simply calling other @Bean methods in the same
class.
❖ The simplest possible @Configuration class would read as follows:

Instantiating the Spring container using


AnnotationConfigApplicationContext
As mentioned above, AnnotationConfigApplicationContext is not limited
to working only with @Configuration classes.
Any @Component or JSR-330 annotated class may be supplied as input
to the constructor. For example:

Bean aliasing
it is sometimes desirable to give a single bean multiple names, otherwise
known as bean aliasing. The name attribute of the @Bean annotation
accepts a String array for this purpose.

Aspect Oriented Programming with Spring

❖ Aspect-Oriented Programming (AOP) complements Object-Oriented


Programming (OOP) by providing another way of thinking about
program structure.
❖ The key unit of modularity in OOP is the class, whereas in AOP the
unit of modularity is the aspect. Aspects enable the modularization
of concerns such as transaction management that cut across multiple
types and objects. (Such concerns are often termed crosscutting
concerns in AOP literature.)
❖ One of the key components of Spring is the AOP framework. While
the Spring IoC container does not depend on AOP, meaning you do
not need to use AOP if you don’t want to, AOP complements Spring
IoC to provide a very capable middleware solution.
AOP is used in the Spring Framework to…
• … provide declarative enterprise services, especially as a replacement for
EJB declarative services.
The most important such service is declarative transaction management.
• … allow users to implement custom aspects, complementing their use of
OOP with AOP.

AOP concepts
❖ • Aspect: a modularization of a concern that cuts across multiple
classes. Transaction management is a good example of a crosscutting
concern in enterprise Java applications.
❖ In Spring AOP, aspects are implemented using regular classes (the
schema-based approach) or regular classes annotated with the
@Aspect annotation (the @AspectJ style).
❖ Join point: a point during the execution of a program, such as the
execution of a method or the handling of an exception. In Spring
AOP, a join point always represents a method execution.
❖ Advice: action taken by an aspect at a particular join point. Different
types of advice include "around," "before" and "after" advice. (Advice
types are discussed below.)
❖ Many AOP frameworks, including Spring, model an advice as an
interceptor, maintaining a chain of interceptors around the join
point.
❖ Pointcut: a predicate that matches join points. Advice is associated
with a pointcut expression and runs at any join point matched by the
pointcut (for example, the execution of a method with a certain
name).
❖ The concept of join points as matched by pointcut expressions is
central to AOP, and Spring uses the AspectJ pointcut expression
language by default
Target object: object being advised by one or more aspects. Also
referred to as the advised object.
Since Spring AOP is implemented using runtime proxies, this object
will always be a proxied object.

AOP proxy: an object created by the AOP framework in order to


implement the aspect contracts (advise method executions and so
on). In the Spring Framework, an AOP proxy will be a JDK dynamic
proxy or a CGLIB proxy.

• Weaving: linking aspects with other application types or objects to


create an advised object.
This can be done at compile time (using the AspectJ compiler, for
example), load time, or at runtime.
Spring AOP, like other pure Java AOP frameworks, performs weaving
at runtime.

Types of advice:
• Before advice: Advice that executes before a join point, but which
does not have the ability to prevent execution flow proceeding to the
join point (unless it throws an exception).

After returning advice: Advice to be executed after a join point


completes normally: for example, if a method returns without
throwing an exception.

After throwing advice: Advice to be executed if a method exits by


throwing an exception.

After (finally) advice: Advice to be executed regardless of the means


by which a join point exits (normal or exceptional return).

Around advice:Advice that surrounds a join point such as a method


invocation. This is the most powerful kind of advice. Around advice
can perform custom behavior before and after the method
Invocation.
It is also responsible for choosing whether to proceed to the join
point or to shortcut the advised method execution by returning its
own return value or throwing an exception.

Enabling @AspectJ Support with XML configuration


To enable @AspectJ support with XML based configuration use the
aop:aspectj-autoproxy element:

Declaring a pointcut
Combining pointcut expressions

Declaring advice
Advice is associated with a pointcut expression, and runs before,
after, or around method executions matched by the pointcut.
The pointcut expression may be either a simple reference to a named
pointcut, or a pointcut expression declared in place.

After returning advice


After returning advice runs when a matched method execution
returns normally. It is declared using the @AfterReturning
annotation:

After throwing advice


After throwing advice runs when a matched method execution exits
by throwing an exception. It is declared using the @AfterThrowing
annotation:

After (finally) advice


❖ After (finally) advice runs however a matched method
execution exits. It is declared using the @After annotation.
❖ After advice must be prepared to handle both normal and
exception return conditions. It is typically used for releasing
resources, etc.

Around advice
❖ The final kind of advice is around advice. Around advice runs
"around" a matched method execution.
❖ It has the opportunity to do work both before and after the
method executes, and to determine when, how, and even if, the
method actually gets to execute at all.
Data Access
Spring Framework integrates with
❖ Transaction Management
❖ DAO support
❖ Data access with JDBC
❖ Object Relational Mapping (ORM) Data Access
❖ Marshalling XML using O/X Mappers
Transaction Management: Comprehensive transaction support is among
the most compelling reasons to use the Spring Framework. The Spring
Framework provides a consistent abstraction for transaction management
that delivers the following benefits:
❖ • Consistent programming model across different transaction APIs
such as Java Transaction API (JTA), JDBC, Hibernate, Java Persistence
API (JPA), and Java Data Objects (JDO).
❖ Support for declarative transaction management.
❖ • Simpler API for programmatic transaction management than
complex transaction APIs such as JTA.
❖ • Excellent integration with Spring’s data access abstractions.

Global transactions
Global transactions enable you to work with multiple transactional
resources, typically relational databases and message queues.
The application server manages global transactions through the
JTA, which is a cumbersome API to use (partly due to its exception model).
Local transactions
❖ Local transactions are resource-specific, such as a transaction
associated with a JDBC connection.
❖ Local transactions may be easier to use, but have significant
disadvantages:
❖ They cannot work across multiple transactional resources. For
example, code that manages transactions using a JDBC connection
cannot run within a global JTA transaction. Because the application
server is not involved in transaction management, it cannot help
ensure correctness across multiple resources. (It is worth noting
that most applications use a single transaction resource.)
❖ Another downside is that local transactions are invasive to the
programming model.
Data access with JDBC
You can choose among several approaches to form the basis for your JDBC
database access. In addition to three flavors of the JdbcTemplate, a new
SimpleJdbcInsert and SimplejdbcCall approach optimizes database
metadata, and the RDBMS Object style takes a more object-oriented
approach similar to that of JDO Query design. Once you start using one of
these approaches, you can still mix and match to include a feature from a
different approach. All approaches require a JDBC 2.0-compliant
driver, and some advanced features require a JDBC 3.0 driver.

Package hierarchy
The Spring Framework’s JDBC abstraction framework consists of four
different packages, namely core, datasource, object, and support.

Spring Jdbc
➢ JdbcTemplate is the classic Spring JDBC approach and the most
popular. This is the "lowest level" approach and all others use a
JdbcTemplate under the covers.
➢ NamedParameterJdbcTemplate wraps a JdbcTemplate to
provide named parameters instead of the traditional JDBC "?"
placeholders. This approach provides better documentation
and ease of use when you have multiple parameters for an SQL
statement.
➢ The Spring Framework’s JDBC abstraction framework consists
of four different packages, namely core, datasource, object, and
support.
➢ The org.springframework.jdbc.core package contains the
JdbcTemplate class and its various callback interfaces.
➢ The org.springframework.jdbc.datasource package contains a
utility class for easy DataSource access, and various simple
DataSource implementations that can be used for testing and
running.
➢ The org.springframework.jdbc.object package contains classes
that represent RDBMS queries, updates, and stored procedures
as thread safe, reusable objects.
➢ The org.springframework.jdbc.support package provides
SQLException translation functionality and some utility
classes.
❖ JdbcTemplate
➢ JdbcTemplate class is the central class in the JDBC core
package.
➢ It handles the creation and release of resources.(connection ,
statement ... etc).

❖ NamedParameterJdbcTemplate
❖o The NamedParameterJdbcTemplate class wraps a JdbcTemplate,
and delegates to the wrapped JdbcTemplate to do much of its work.
❖o The NamedParameterJdbcTemplate class adds support for
programming JDBC statements using named parameters, as opposed
to programming JDBC statements using only classic placeholder ( '?')
arguments.

Example :
Hibernate

ØWhat is Hibernate?

ØAdvantages of Hibernate ?
ØWhat ORM does ?
ØHow to save a Java Object with Hibernate?
Ø All the CRUD operations are handled by Hibernate.

Ø What does sessionFactory & session ?

SessionFactory setup in a Spring container


To avoid tying application objects to hard-coded resource lookups,
you can define resources such as a JDBC DataSource or a Hibernate
SessionFactory as beans in the Spring container. Application objects
that need to access resources receive references to such predefined
instances through bean references.

Spring’s LocalSessionFactoryBean supports Hibernate


SessionFactory.getCurrentSession() method for any Spring
transaction strategy, returning the current Spring-managed
transactional Session even with HibernateTransactionManager. Of
of course, the standard behavior of that method remains the return
of the current Session associated with the ongoing JTA transaction.

You annotate the service layer with @Transactional annotations and


instruct the Spring container to find these annotations and provide
transactional semantics for these annotated methods.

All you need to provide is the TransactionManager implementation


and a "<tx:annotation-driven/>" entry.
Refer to the example programme.

The Web
Web MVC framework
❖ The Spring Web model-view-controller (MVC) framework is
designed around a DispatcherServlet that dispatches requests
to handlers, with configurable handler mappings, view
resolution, locale, time zone and theme resolution as well as
support for uploading files.
❖ The default handler is based on the @Controller and
@RequestMapping annotations, offering a wide range of
flexible handling methods.
❖ With the introduction of Spring 3.0, the @Controller
mechanism also allows you to create RESTful Web sites and
applications, through the @PathVariable annotation and other
features.
❖ In Spring Web MVC you can use any object as a command or
form-backing object; you do not need to implement a
framework-specific interface or base class. Spring’s data
binding is highly flexible: example, it treats type mismatches as
validation errors that can be evaluated by the application, not
as system errors. Thus you need not duplicate your business
objects' properties as simple, untyped strings
❖ In your form objects simply to handle invalid submissions, or to
convert the Strings properly. Instead, it is often preferable to
bind directly to your business objects.

Spring’s view resolution is extremely flexible. A Controller is


typically responsible for preparing a model Map with data and
selecting a view name but it can also write directly to the
response stream and complete the request. View name
resolution is highly configurable through file extension
or Accept header content type negotiation, through bean
names, a properties file, or even a custom ViewResolver
implementation. The model (the M in MVC) is a Map interface,
which allows for the complete abstraction of the view
technology. You can integrate directly with template based
rendering technologies such as JSP, Velocity and Freemarker, or
directly generate XML, JSON, Atom, and many other types of
content. The model Map is simply transformed into an
appropriate format, such as JSP request attributes, a Velocity
template model.
Spring’s web module includes many unique web support
features:
❖ Clear separation of roles. Each role—controller, validator,
command object, form object, model object,
DispatcherServlet, handler mapping, view resolver, and
so on—can be fulfilled by a specialized object.
❖ Powerful and straightforward configuration of both
framework and application classes as JavaBeans.
❖ This configuration capability includes easy referencing
across contexts, such as from web controllers
to business objects and validators.
❖ • Adaptability, non-intrusiveness, and flexibility. Define
any controller method signature you need, possibly using
one of the parameter annotations (such as
@RequestParam, @RequestHeader, @PathVariable, and
more) for a given scenario.
❖ Reusable business code, no need for duplication. Use
existing business objects as command or form objects
instead of mirroring them to extend a particula
framework base class.
❖ Customizable binding and validation. Type mismatches
as application-level validation errors that keep
the offending value, localized date and number binding,
and so on instead of String-only form objects
with manual parsing and conversion to business objects.
The DispatcherServlet
Spring’s web MVC framework is, like many other web MVC frameworks,
request-driven, designed around a central Servlet that dispatches requests
to controllers and offers other functionality that facilitates the
development of web applications. Spring’s DispatcherServlet however, does
more
than just that. It is completely integrated with the Spring IoC container
and as such allows you to use every other feature that Spring has.

The DispatcherServlet is an actual Servlet (it inherits from the HttpServlet


base class), and as such is declared in the web.xml of your web application.
You need to map requests that you want the
DispatcherServlet to handle, by using a URL mapping in the same web.xml
file. This is standard Java EE Servlet configuration; the following example
shows such a DispatcherServlet declaration and mapping:
In the preceding example, all requests starting with /example will be
handled by the DispatcherServlet instance named example. In a Servlet
3.0+ environment, you also have the option of configuring the Servlet
container programmatically. Below is the code based equivalent of the
above web.xml example:

WebApplicationInitializer is an interface provided by Spring MVC that


ensures your code-based configuration is detected and automatically used
to initialize any Servlet 3 container. An abstract base class implementation
of this interface named AbstractDispatcherServletInitializer makes it
even easier to register the DispatcherServlet by simply specifying its
servlet mapping.
Upon initialization of a DispatcherServlet, Spring MVC looks for a file
named [servlet-name]- servlet.xml in the WEB-INF directory of your web
application and creates the beans defined there, overriding the definitions
of any beans defined with the same name in the global scope.

Consider the following DispatcherServlet Servlet configuration (in the


web.xml file):
With the above Servlet configuration in place, you will need to have a file
called /WEB-INF/golfing servlet. xml in your application; this file will
contain all of your Spring Web MVC-specific components (beans). You can
change the exact location of this configuration file through a Servlet
initialization
parameter (see below for details).

DispatcherServlet Processing Sequence


After you set up a DispatcherServlet, and a request comes in for that
specific DispatcherServlet, the DispatcherServlet starts processing the
request as follows:

❖ The WebApplicationContext is searched for and bound in the request


as an attribute that the controller and other elements in the process
can use. It is bound by default under the key
DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE.

❖ The locale resolver is bound to the request to enable elements in the


process to resolve the locale to use when processing the request
(rendering the view, preparing data, and so on). If you do not
need locale resolving, you do not need it.
❖ An appropriate handler is searched for. If a handler is found, the
execution chain associated with the handler (preprocessors,
postprocessors, and controllers) is executed in order to prepare a
model or rendering.
❖ Spring 2.5 introduced an annotation-based programming model for
MVC controllers that uses annotations such as @RequestMapping,
@RequestParam, @ModelAttribute, and so on.
❖ This annotation support is available for both Servlet MVC and Portlet
MVC. Controllers implemented in this style do not have to extend
specific base classes or implement specific interfaces. Furthermore,
they do not usually have direct dependencies on Servlet or Portlet
APIs, although you can easily configure access to Servlet or Portlet
facilities.


❖ Defining a controller with @Controller
The @Controller annotation indicates that a particular class serves the
role of a controller. Spring does not require you to extend any controller
base class or reference the Servlet API. However, you can still reference
Servlet-specific features if you need to.
The @Controller annotation acts as a stereotype for the annotated class,
indicating its role. The dispatcher scans such annotated classes for mapped
methods and detects @RequestMapping annotations.

Mapping Requests With @RequestMapping


You use the @RequestMapping annotation to map URLs such as
/appointments onto an entire class or a particular handler method.
Typically the class-level annotation maps a specific request
path (or path pattern) onto a form controller, with additional method-level
annotations narrowing the primary mapping for a specific HTTP method
request method ("GET", "POST", etc.) or an HTTP request parameter
condition.

A method can have any number of @PathVariable annotations:


When a @PathVariable annotation is used on a Map<String, String>
argument, the map is populated with all URI template variables.
A URI template can be assembled from type and path level
@RequestMapping annotations. As a result
the findPet() method can be invoked with a URL such as
/owners/42/pets/21.

Mapping the request body with the @RequestBody annotation


The @RequestBody method parameter annotation indicates that a method
parameter should be bound to the value of the HTTP request body. For
example:

You convert the request body to the method argument by using an


HttpMessageConverter. HttpMessageConverter is responsible for
converting from the HTTP request message to an object
and converting from an object to the HTTP response body. The
RequestMappingHandlerAdapter supports the @RequestBody annotation
with the following default HttpMessageConverters.

Mapping the response body with the @ResponseBody annotation


The @ResponseBody annotation is similar to @RequestBody. This
annotation can be put on a method and indicates that the return type
should be written straight to the HTTP response body (and not placed
in a Model, or interpreted as a view name).
For example:

Creating REST Controllers with the @RestController annotation


It’s a very common use case to have Controllers implement a REST API,
thus serving only JSON, XML or custom MediaType content. For
convenience, instead of annotating all your @RequestMapping
methods with @ResponseBody, you can annotate your Controller Class
with @RestController.
Resolving views
All MVC frameworks for web applications provide a way to address views.
Spring provides view resolvers, which enable you to render models in a
browser without tying you to a specific view technology. Out of the box,
Spring enables you to use JSPs, Velocity templates and XSLT views, for
Example.
The two interfaces that are important to the way Spring handles views are
ViewResolver and View.
The ViewResolver provides a mapping between view names and actual
views. The View interface addresses the preparation of the request and
hands the request over to one of the view technologies.
InternalResourceViewResolver: Convenient subclass of
UrlBasedViewResolver that supports InternalResourceView (in effect,
Servlets and JSPs) and subclasses such as JstlView and TilesView. You can
specify the view class for all views generated by this resolver
by using setViewClass(..). See the UrlBasedViewResolver javadocs for
details.
The Model ModelMap (ModelAndView)
The ModelMap class is essentially a glorified Map that can make adding
objects that are to be displayed in (or on) a View adhere to a common
naming convention. Consider the following Controller implementation;
notice that objects are added to the ModelAndView without any associated
name specified.
The ModelAndView class uses a ModelMap class that is a custom Map
implementation that automatically generates a key for an object when an
object is added to it. The strategy for determining the name for an added
object is, in the case of a scalar object such as User, to use the short class
name of the object’s class. The following examples are names that are
generated for scalar objects put into a ModelMap instance.
Enabling the MVC Java Config or the MVC XML Namespace
To enable MVC Java config add the annotation @EnableWebMvc to one of
your @Configuration classes:
Describe the Front Controller Pattern

In the Front Controller pattern, all requests will first go to the front controller
instead of the servlet. It'll make sure that the responses are ready and will
send them back to the browser. This way we have one place where we control
everything that comes from the outside world.

The front controller will identify the servlet that should handle the request
first. Then, when it gets the data back from the servlet, it'll decide which view
to render and, finally, it'll send the rendered view back as a response:
What Are Model 1 and Model 2 Architectures?

Model 1 and Model 2 represent two frequently used design models when it
comes to designing Java Web Applications.

In Model 1, a request comes to a servlet or JSP where it gets handled. The


servlet or the JSP processes the request, handles business logic, retrieves and
validates data, and generates the response:
ince this architecture is easy to implement, we usually use it in small and
simple applications.

On the other hand, it isn't convenient for large-scale web applications. The
functionalities are often duplicated in JSPs where business and presentation
logic are coupled.

The Model 2 is based on the Model View Controller design pattern and it
separates the view from the logic that manipulates the content.

Furthermore, we can distinguish three modules in the MVC pattern: the


model, the view, and the controller. The model is representing the dynamic
data structure of an application. It's responsible for the data and business
logic manipulation. The view is in charge of displaying the data, while the
controller serves as an interface between the previous two.

In Model 2, a request is passed to the controller, which handles the required


logic in order to get the right content that should be displayed. The controller
then puts the content back into the request, typically as a JavaBean or a POJO.
It also decides which view should render the content and finally passes the
request to it. Then, the view renders the data:

Name the annotations used to handle different types of incoming


HTTP request methods?
The following annotations are used to handle different types of incoming HTTP request methods: -

● @GetMapping

● @PostMapping

● @PutMapping

● @PatchMapping

● @DeleteMapping

What is the purpose of @PathVariable annotation in Spring


MVC?

The @PathVariable annotation is used to extract the value of the URI template. It is passed within the

parameters of the handler method.


For example :-

@RequestMapping("/show/{id}")

public String handler(@PathVariable("id") String s, Model map)

What are the ways of reading data from the form in Spring
MVC?
The following ways to read the data from the form are: -

● HttpServletRequest interface - The HttpServletRequest is a java interface present in

javax.servlet.http package. Like Servlets, you can use HttpServletRequest in Spring to read the

HTML form data provided by the user.

● @RequestParam annotation - The @RequestParam annotation reads the form data and binds it

automatically to the parameter present in the provided method.

● @ModelAttribute annotation - The @ModelAttribute annotation binds a method parameter or

its return value to a named model attribute.

What is Bean Validation API?

The Bean Validation API is a Java specification which is used to apply constraints on object models via

annotations. Here, we can validate a length, number, regular expression, etc. Apart from that, we can

also provide custom validations.


As Bean Validation API is just a specification, it requires an implementation. So, for that, it uses

Hibernate Validator. The Hibernate Validator is a fully compliant JSR-303/309 implementation that

allows to express and validate application constraints.

What is the use of @Valid annotation in Spring MVC?

The @Valid annotation is used to apply validation rules on the provided object.

How to validate a user's input within a number range in Spring


MVC?

In Spring MVC Validation, we can validate the user's input within a number range by using the following

annotations: -

● @Min annotation - It is required to pass an integer value with @Min annotation. The user input

must be equal to or greater than this value.

● @Max annotation - It is required to pass an integer value with @Max annotation. The user input

must be equal to or smaller than this value.

Spring Framework
❖ Spring Framework Introduction
❖ Spring Framework is a Java platform based framework , that provides
comprehensive infrastructure support for developing Java
applications.
❖ Spring handles the infrastructure so developers can focus on
application development/Business logic .
❖ The Spring Framework is divided into modules. Applications can
choose which modules they need. At the heart are the modules of the
core container, including a configuration model and a dependency
injection mechanism.
❖ Spring came into being in 2003 as a response to the complexity of
the early J2EE specifications.
❖ Beyond the Spring Framework, there are other projects, such as
Spring Boot, Spring Security, Spring Data, Spring Cloud, Spring Batch,
among others.
❖ Guiding principles of the Spring Framework
■ · Provide choice at every level
■ · Accommodate diverse perspectives
■ · Maintain strong backward compatibility
■ · Care about API design
■ · Set high standards for code quality
❖ As mentioned above Spring is a vast framework, Some important
modules given below
★· Spring Core
★· Spring AOP
★· Spring JDBC
★· Spring Transaction
★· Spring ORM
★· Spring MVC
❖ All the modules of Spring are independent of each other except
Spring Core. As Spring core is the base module, so in all modules we
have to use Spring Core.
❖ The Major features of Spring framework are
■ · Inversion Of Control
■ · Dependency Injection.

Core Container

❖ The Core Container consists of the Core, Beans, Context, and


Expression Language modules.
❖ The Core and Beans modules provide the fundamental parts of the
framework, including the IoC and Dependency Injection features.
The BeanFactory is a sophisticated implementation of the factory
❖ It removes the need for programmatic singletons and allows you to
decouple the configuration and specification of dependencies from
your actual program logic.
❖ The Context module builds on the solid base provided by the Core
and Beans modules: it is a means to access objects in a
framework-style manner that is similar to a JNDI registry.
❖ The Context module inherits its features from the Beans module and
adds support for internationalization (using, for example,resource
bundles), event-propagation, resource-loading, and the transparent
creation of contexts.
❖ for example, a servlet container. The Context module also supports
Java EE features such as EJB, JMX ,and basic remoting. The
ApplicationContext interface is the focal point of the Context
module.
❖ The Expression Language module provides a powerful expression
language for querying and manipulating an object graph at runtime.
It is an extension of the unified expression language (unified EL) as
specified in the JSP 2.1 specification. The language supports setting
and getting property values.
❖ property assignment, method invocation, accessing the context of
arrays, collections and indexers.
❖ logical and arithmetic operators, named variables, and retrieval of
objects by name from Spring’s IoC container. It also supports list
projection and selection as well as common list aggregations.

Data Access/Integration
❖ The Data Access/Integration layer consists of the JDBC, ORM,
OXM, JMS and Transaction modules.
❖ The JDBC module provides a JDBC-abstraction layer that
removes the need to do tedious JDBC coding and parsing of
database-vendor specific error codes.
❖ The ORM module provides integration layers for popular
object-relational mapping APIs, including JPA, JDO, and
Hibernate.
❖ Using the ORM package you can use all of these O/R-mapping
frameworks in combination with all of the other features Spring
offers, such as the simple declarative transaction management
feature mentioned previously.
❖ 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 (plain old Java
objects).

Web

❖ The Web layer consists of the Web, Web-Servlet, WebSocket


and Web-Portlet modules.
❖ Spring’s 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.
❖ It also contains the web-related parts of Spring’s remoting
support.
❖ The Web-Servlet module contains Spring’s
model-view-controller (MVC) implementation for web
applications. Spring’s MVC framework provides a clean
separation between domain model code and web forms, and
integrates with all the other features of the Spring Framework.
❖ The Web-Portlet module provides the MVC implementation to
be used in a portlet environment and mirrors the functionality
of the Web-Servlet module.

AOP and Instrumentation

❖ Spring’s AOP module provides an AOP Alliance-compliant


aspect-oriented programming implementation allowing you to
define.
❖ For example, method-interceptors and pointcuts to cleanly
decouple code that implements functionality that should be
separated.
❖ Using source-level metadata functionality, you can also
incorporate behavioral information into your code, in a manner
similar to that of .NET attributes.
❖ The separate Aspects module provides integration with
AspectJ.
❖ The Instrumentation module provides class instrumentation
support and classloader implementations to be used in certain
application servers.
Typical full-fledged Spring web application.

Dependency Management and Naming Conventions

Dependency management and dependency injection are different things.


To get those nice features of Spring into your application (like dependency
injection) you need to assemble all the libraries needed (jar files) and get
them onto your classpath at runtime, and possibly at compile time. These
dependencies are not virtual components that are injected, but physical
resources in a file system (typically).
The process of dependency management involves locating those resources,
storing them and adding them to classpaths. Dependencies can be direct
(e.g. my application depends on Spring at runtime), or indirect

(e.g. my application depends on commons-dbcp which depends on


commons-pool).

The indirect dependencies are also known as "transitive" and it is those


dependencies that are hardest to identify and manage.

If you are going to use Spring you need to get a copy of the jar libraries that
comprise the pieces of Spring that you need. To make this easier Spring is
packaged as a set of modules that separate the dependencies as much as
possible, so for example if you don’t want to write a web application you

don’t need the spring-web modules. To refer to Spring library modules in


this guide we use a shorthand naming convention spring-* or spring-*.jar,
where * represents the short name for the module

(e.g. spring-core, spring-webmvc, spring-jms, etc.). The actual jar file name
that you use is normally the module name concatenated with the version
number (e.g. spring-core-4.0.9.RELEASE.jar).

Each release of the Spring Framework will publish artifacts to the following
places:

• Maven Central, which is the default repository that Maven queries, and
does not require any special configuration to use. Many of the common
libraries that Spring depends on also are available from Maven Central and
a large section of the Spring community uses Maven for dependency
management, so this is convenient for them. The names of the jars here are
in the form spring-*-

<version>.jar and the Maven groupId is org.springframework.


• In a public Maven repository hosted specifically for Spring. In addition to
the final GA releases, this repository also hosts development snapshots and
milestones. The jar file names are in the same form as Maven Central, so
this is a useful place to get development versions of Spring to use with
other libraries deployed in Maven Central. This repository also contains a
bundle distribution zip file that contains all Spring jars bundled together
for easy download.

So the first thing you need to decide is how to manage your dependencies:
we generally recommend the use of an automated system like Maven,
Gradle or Ivy, but you can also do it manually by downloading all the jars

Logging

Logging is a very important dependency for Spring because

a) it is the only mandatory external dependency.

b) everyone likes to see some output from the tools they are using, and

c) Spring integrates with lots of other tools all of which have also made a
choice of logging dependency.

One of the goals of an application developer is often to have unified


logging configured in a central place for the whole

application, including all external components. This is more difficult than


it might have been since there are so many choices of logging framework.

The mandatory logging dependency in Spring is the Jakarta Commons


Logging API (JCL). We compile against JCL and we also make JCL Log
objects visible for classes that extend the Spring Framework.
❖ Inversion of Control (IoC) is a design principle (although, some
people refer to it as a pattern). As the name suggests, it is used to
invert different kinds of controls in object-oriented design to achieve
loose coupling.

❖ The core of spring framework is it’s bean factory and mechanisms to


create and manage such beans inside Spring container. The beans in
the spring container can be created in five scopes .
❖ How can containers manage beans ?

What are the advantages of Spring framework?


❖ Lightweight: Spring is lightweight. The basic version of the Spring
framework is around 2MB.
❖ Dependency Injection/Inversion of Control (IoC): This helps to
achieve loose coupling by wiring of independent components/objects
❖ Spring Container: contains and manages the lifecycle of the
application objects
❖ Transaction Management: Spring supports the transaction
management i.e. JDBC operation, File uploading, Exception Handling
etc either by spring annotation or bean configuration.
❖ Spring MVC: Spring MVC can be used to create Web application as
well as restful web services which is capable of returning XML or
JSON response
❖ Exception Handling: Spring provides a convenient API to translate
technology specific exceptions (thrown by JDBC, Hibernate etc) into
consistent unchecked exceptions
❖ Aspect Oriented Programming(AOP): AOP breaks the program logic
into distinct parts (called concerns). It is used to increase modularity
by cross-cutting concerns. A cross-cutting concern is a concern that
can affect the whole application and should be centralized in one
location in code as possible, such as transaction management,
authentication, logging, security etc

❖ What is Spring Bean?


❖ Any normal Java class that is initialized by a Spring IoC
container is called Spring Bean. We use spring application
context to get Spring Bean instances. Spring IoC Container
manages the lifecycle of Spring Bean scope and injects any
required dependencies in the bean.

❖ Different scopes of Spring bean ?


❖ When we declare <bean>, we can specify the scope of the bean
to inform the IoC container about the creation of the bean and
how long it will survive.
❖ For any java application there are two different scopes called
singleton and prototype.
❖ There are three different scopes i.e. request, session and
global-session specially for spring based java Web applications.
❖ Singleton is the default scope of any bean. This means a single
instance of the bean will get created per IoC container. Hence
the Singleton beans are not thread safe.
❖ In prototype scope a new instance will get created every time
the bean is requested.
❖ In request scope, a bean is defined to an HTTP request. This
scope is valid only in a web-aware spring ApplicationContext.
❖ In session scope, a bean is defined to an HTTP session. This
scope is valid only in a web-aware spring ApplicationContext.
❖ In global-session scope, a bean is defined to a global HTTP
session. This scope is valid only in a web-aware spring
ApplicationContext.
❖ To set the scope of the spring bean, we can use the scope
attribute in <bean> tag. @scope is used in annotation based DI.

Spring IoC Container


❖ 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 dependency injection (DI) to
manage the components that make up an application.
There are two different types of containers
BeanFactory container: This is the heart of the Spring
container. org.springframework.beans.factory.BeanFactory is
an interface and acts as a IoC container which instantiates,
configures, and manages a number of beans.
❖ ApplicationContext container:
org.springframework.context.ApplicationContext
interface also acts as the IoC container but the
ApplicationContext interface is built on top of the
BeanFactory interface to provides some extra
functionality than BeanFactory such as simple
integration with Spring’s AOP, message resource handling
(for I18N), event propagation, application layer specific
context (e.g. WebApplicationContext) for web
application. So it is better to use ApplicationContext than
BeanFactory.

@Autowired
❖ For annotation based dependency injection, @Autowired
annotation is used. The classes marked with
@Component/@Service/@Repository etc can be injected
to the property which is marked with @Autowired

@Autowired is applied to
❖ field: for the field-based dependency injection
❖ setter for the setter dependency injection. Same as
field-based dependency injection.
❖ constructor for constructor-based dependency injection.

Difference between constructor based and setter based DI ?


❖ Injection of dependencies can be optional or mandatory.
For mandatory injection we use constructor based DI. While for
the optional dependencies we can use setter based DI. However,
we can mark a setter based DI with @Required annotation.
❖ In case of cyclic dependency, constructor based DI won’t
be able to inject but setter based DI would be able to inject
❖ If more number of parameters to be injected then it is
advisable to use constructor based DI.

Difference between context:annotation-config and


context:component-scan ?
❖ context:annotation-config is used to activate annotations in beans
already registered in the application context .
❖ context:component-scan can also do what context:annotation-config
does but also scans packages to find and register beans within the
application context.

Difference between @Component, @Controller, @Repository & @Service


annotations ?
If a class is marked with
@Component/@Controller/@Service/@Repository annotation then the
spring DI container can identify the class during component scan
mechanism. However, it is a good idea to use @Service for service layer
classes, and @Controller should be used in spring mvc web controller.
@Repository is used to import DAOs into DI containers. Also any
unchecked exception will get translated into Spring DataAccessException.

Transaction management in Spring


Database transaction is a set of actions treated as the unit of work. Main
principle of a transaction is either commit all actions or rollback
everything in case of failure. While committing data in a transaction, we
need to ensure the transaction agreement/properties called ACID
(Atomicity-Consistency-Isolation-Durability)

❖ Atomicity: All operations in a transaction are considered as a unit of


work. Hence, a transaction will be either committed or roll backed.
❖ Consistency: This ensures that a transaction will bring the database
from one valid state to another valid state by maintaining the
referential integrity of the database
❖ Isolation: Each transaction should be isolated from other
transactions even though they are working on the same set of data.
❖ Durability: This ensures that once a transaction is completed, the
data will be made permanent in the database. The data will not get
lost even after power loss or system crash.
❖ Spring supports both Programmatic and Declarative transaction
management. It also supports Global and Local transactions.

Dependencies and configuration in detail


Straight values (primitives, Strings, and so on)
The value attribute of the <property/> element specifies a property or
constructor argument as a human-readable string representation.
Spring’s conversion service is used to convert these values from
a String to the actual type of the property or argument.

You can also configure a java.util.Properties instance as:


The Spring container converts the text inside the <value/> element into a
java.util.Properties instance by using the JavaBeans PropertyEditor
mechanism. This is a nice shortcut, and is one of
a few places where the Spring team do favor the use of the nested <value/>
element over the value attribute style.

The idref element


The idref element is simply an error-proof way to pass the id (string value -
not a reference) of another
bean in the container to a <constructor-arg/> or <property/> element.

Collections
In the <list/>, <set/>, <map/>, and <props/> elements, you set the
properties and arguments of
the Java Collection types List, Set, Map, and Properties, respectively.
Lazy-initialized beans
➔ By default, ApplicationContext implementations eagerly create and
configure all singleton beans as part of the initialization process.
➔ Generally, this pre-instantiation is desirable, because errors in the
➔ configuration or surrounding environment are discovered
immediately, as opposed to hours or even days later.
➔ When this behavior is not desirable, you can prevent
pre-instantiation of a singleton bean by marking the bean definition
as lazy-initialized.
➔ A lazy-initialized bean tells the IoC container to create a
➔ bean instance when it is first requested, rather than at startup.
➔ In XML, this behavior is controlled by the lazy-init attribute on the
<bean/> element;

➔ When the preceding configuration is consumed by an


ApplicationContext, the bean named lazy is not eagerly
pre-instantiated when the ApplicationContext is starting up,
whereas the not. Lazy bean is eagerly pre-instantiated.
➔ However, when a lazy-initialized bean is a dependency of a
singleton bean that is not lazy-initialized, the
ApplicationContext creates the lazy-initialized bean at startup,
because it must satisfy the singleton’s dependencies.
➔ The lazy-initialized bean is injected into a singleton bean
elsewhere that is not lazy-initialized.

Autowiring collaborators
➔ The Spring container can autowire relationships between
collaborating beans.
➔ You can allow Spring to resolve collaborators (other beans)
automatically for your bean by inspecting the contents of the
ApplicationContext.

Autowiring has the following advantages:


• Autowiring can significantly reduce the need to specify properties or
constructor arguments. (Other mechanisms such as a bean template
discussed elsewhere in this chapter are also valuable in this regard.)
• Autowiring can update a configuration as your objects evolve. For
example, if you need to add a dependency to a class, that dependency can
be satisfied automatically without you needing to modify the
configuration. Thus autowiring can be especially useful during
development, without negating the option of switching to explicit wiring
when the code base becomes more stable.
When using XML-based configuration metadata 10, you specify autowire
mode for a bean definition with the autowire attribute of the <bean/>
element.
The autowiring functionality has different modes. You specify autowiring
per bean and thus can choose which ones to autowire.
❖ No
❖ byName
❖ byType
❖ constructor

PropertyPlaceholderConfigurer
❖ You use the PropertyPlaceholderConfigurer to externalize property
values from a bean definition in a separate file using the standard
Java Properties format.
❖ Doing so enables the person deploying an application to customize
environment-specific properties such as database URLs and
passwords, without the complexity or risk of modifying the main
XML definition file or files for the container.
❖ Consider the following XML-based configuration metadata fragment,
where a DataSource with placeholder values is defined.
❖ The example shows properties configured from an external
Properties file. At runtime, a PropertyPlaceholderConfigurer is
applied to the metadata that will replace some properties of the
DataSource.
❖ The values to replace are specified as placeholders of the form
${property-name} which follows the Ant / log4j / JSP EL style.
❖ Therefore, the string ${jdbc.username} is replaced at runtime with
the values , and the same applies for other placeholder values that
match keys in the properties file.
❖ The PropertyPlaceholderConfigurer checks for placeholders in most
properties and attributes of a bean definition. Furthermore, the
placeholder prefix and suffix can be customized.
<context:property-placeholder
location="classpath:com/foo/jdbc.properties"/>

@Required
The @Required annotation applies to bean property setter methods, as in
the following example:
❖ This annotation simply indicates that the affected bean property
must be populated at configuration time, through an explicit
property value in a bean definition or through autowiring.
❖ The container throws an exception if the affected bean property has
not been populated; this allows for eager and explicit failure,
avoiding NullPointerExceptions or the like later on.
❖ It is still recommended that you put assertions into the bean class
itself, for example, into an init method. Doing so enforces those
required references and values even when you use the class outside of
a container.

@Autowired
As expected, you can apply the @Autowired annotation to "traditional"
setter methods:
❖ You can also apply the annotation to methods with arbitrary names
and/or multiple arguments.
❖ You can apply @Autowired to constructors and fields.

Fine-tuning annotation-based autowiring with qualifiers


Because autowiring by type may lead to multiple candidates, it is often
necessary to have more control over the selection process.
One way to accomplish this is with Spring’s @Qualifier annotation
The @Qualifier annotation can also be specified on individual constructor
arguments or method parameters:

@PostConstruct and @PreDestroy


❖ The CommonAnnotationBeanPostProcessor not only recognizes the
@Resource annotation but also the JSR-250 lifecycle annotations.
Introduced in Spring 2.5, the support for these annotations offers yet
another alternative to those described in initialization callbacks and
destruction callbacks.
❖ Provided that the CommonAnnotationBeanPostProcessor is
registered within the Spring ApplicationContext, a method carrying
one of these annotations is invoked at the same point in the lifecycle
as the corresponding Spring lifecycle interface method or explicitly
declared callback method.
❖ In the example below, the cache will be pre-populated upon
initialization and cleared upon destruction
Automatically detecting classes and registering bean definitions
❖ Spring can automatically detect stereotyped classes and register
corresponding BeanDefinitions with the ApplicationContext.
❖ For example, the following two classes are eligible for such
autodetection:
To autodetect these classes and register the corresponding beans,
you need to include the following element in XML, where the
base-package element is a common parent package for the two
classes. (Alternatively, you can specify
comma/semicolon/space/tab/line feed- separated list that includes
the parent package of each class.)

The use of <context:component-scan> implicitly enables the functionality


of <context:annotation-config>. There is usually no need to include the
<context:annotation-config> element when using
<context:component-scan>.

Naming autodetected components


When a component is autodetected as part of the scanning process, its
bean name is generated by the BeanNameGenerator strategy known to that
scanner. By default, any Spring stereotype annotation (
@Component, @Repository, @Service, and @Controller) that contains a
name value will thereby provide that name to the corresponding bean
definition.
Providing a scope for autodetected components
As with Spring-managed components in general, the default and most
common scope for autodetected components is singleton.
However, sometimes you need other scopes, which Spring 2.5 provides with
a new @Scope annotation. Simply provide the name of the scope within
the annotation:

Java-based container configuration

Basic concepts: @Bean and @Configuration

❖ The central artifacts in Spring’s new Java-configuration support are


@Configuration-annotated classes and @Bean-annotated methods.
❖ The @Bean annotation is used to indicate that a method
instantiates, configures and initializes a new object to be managed by
the Spring IoC container. For those familiar with Spring’s <beans/>
XML configuration the @Bean annotation plays the same role as the
<bean/> element.
❖ You can use @Bean annotated methods with any Spring
@Component, however, they are most often used with
@Configuration beans.

❖ Annotating a class with @Configuration indicates that its primary


purpose is as a source of bean definitions.
❖ Furthermore, @Configuration classes allow inter-bean dependencies
to be defined by simply calling other @Bean methods in the same
class.
❖ The simplest possible @Configuration class would read as follows:

Instantiating the Spring container using


AnnotationConfigApplicationContext
As mentioned above, AnnotationConfigApplicationContext is not limited
to working only with @Configuration classes.
Any @Component or JSR-330 annotated class may be supplied as input
to the constructor. For example:

Bean aliasing
it is sometimes desirable to give a single bean multiple names, otherwise
known as bean aliasing. The name attribute of the @Bean annotation
accepts a String array for this purpose.

Aspect Oriented Programming with Spring

❖ Aspect-Oriented Programming (AOP) complements Object-Oriented


Programming (OOP) by providing another way of thinking about
program structure.
❖ The key unit of modularity in OOP is the class, whereas in AOP the
unit of modularity is the aspect. Aspects enable the modularization
of concerns such as transaction management that cut across multiple
types and objects. (Such concerns are often termed crosscutting
concerns in AOP literature.)
❖ One of the key components of Spring is the AOP framework. While
the Spring IoC container does not depend on AOP, meaning you do
not need to use AOP if you don’t want to, AOP complements Spring
IoC to provide a very capable middleware solution.
AOP is used in the Spring Framework to…
• … provide declarative enterprise services, especially as a replacement for
EJB declarative services.
The most important such service is declarative transaction management.
• … allow users to implement custom aspects, complementing their use of
OOP with AOP.

AOP concepts
❖ • Aspect: a modularization of a concern that cuts across multiple
classes. Transaction management is a good example of a crosscutting
concern in enterprise Java applications.
❖ In Spring AOP, aspects are implemented using regular classes (the
schema-based approach) or regular classes annotated with the
@Aspect annotation (the @AspectJ style).
❖ Join point: a point during the execution of a program, such as the
execution of a method or the handling of an exception. In Spring
AOP, a join point always represents a method execution.
❖ Advice: action taken by an aspect at a particular join point. Different
types of advice include "around," "before" and "after" advice. (Advice
types are discussed below.)
❖ Many AOP frameworks, including Spring, model an advice as an
interceptor, maintaining a chain of interceptors around the join
point.
❖ Pointcut: a predicate that matches join points. Advice is associated
with a pointcut expression and runs at any join point matched by the
pointcut (for example, the execution of a method with a certain
name).
❖ The concept of join points as matched by pointcut expressions is
central to AOP, and Spring uses the AspectJ pointcut expression
language by default
Target object: object being advised by one or more aspects. Also
referred to as the advised object.
Since Spring AOP is implemented using runtime proxies, this object
will always be a proxied object.

AOP proxy: an object created by the AOP framework in order to


implement the aspect contracts (advise method executions and so
on). In the Spring Framework, an AOP proxy will be a JDK dynamic
proxy or a CGLIB proxy.

• Weaving: linking aspects with other application types or objects to


create an advised object.
This can be done at compile time (using the AspectJ compiler, for
example), load time, or at runtime.
Spring AOP, like other pure Java AOP frameworks, performs weaving
at runtime.

Types of advice:
• Before advice: Advice that executes before a join point, but which
does not have the ability to prevent execution flow proceeding to the
join point (unless it throws an exception).

After returning advice: Advice to be executed after a join point


completes normally: for example, if a method returns without
throwing an exception.

After throwing advice: Advice to be executed if a method exits by


throwing an exception.

After (finally) advice: Advice to be executed regardless of the means


by which a join point exits (normal or exceptional return).

Around advice:Advice that surrounds a join point such as a method


invocation. This is the most powerful kind of advice. Around advice
can perform custom behavior before and after the method
Invocation.
It is also responsible for choosing whether to proceed to the join
point or to shortcut the advised method execution by returning its
own return value or throwing an exception.

Enabling @AspectJ Support with XML configuration


To enable @AspectJ support with XML based configuration use the
aop:aspectj-autoproxy element:

Declaring a pointcut
Combining pointcut expressions

Declaring advice
Advice is associated with a pointcut expression, and runs before,
after, or around method executions matched by the pointcut.
The pointcut expression may be either a simple reference to a named
pointcut, or a pointcut expression declared in place.

After returning advice


After returning advice runs when a matched method execution
returns normally. It is declared using the @AfterReturning
annotation:

After throwing advice


After throwing advice runs when a matched method execution exits
by throwing an exception. It is declared using the @AfterThrowing
annotation:

After (finally) advice


❖ After (finally) advice runs however a matched method
execution exits. It is declared using the @After annotation.
❖ After advice must be prepared to handle both normal and
exception return conditions. It is typically used for releasing
resources, etc.

Around advice
❖ The final kind of advice is around advice. Around advice runs
"around" a matched method execution.
❖ It has the opportunity to do work both before and after the
method executes, and to determine when, how, and even if, the
method actually gets to execute at all.
Data Access
Spring Framework integrates with
❖ Transaction Management
❖ DAO support
❖ Data access with JDBC
❖ Object Relational Mapping (ORM) Data Access
❖ Marshalling XML using O/X Mappers
Transaction Management: Comprehensive transaction support is among
the most compelling reasons to use the Spring Framework. The Spring
Framework provides a consistent abstraction for transaction management
that delivers the following benefits:
❖ • Consistent programming model across different transaction APIs
such as Java Transaction API (JTA), JDBC, Hibernate, Java Persistence
API (JPA), and Java Data Objects (JDO).
❖ Support for declarative transaction management.
❖ • Simpler API for programmatic transaction management than
complex transaction APIs such as JTA.
❖ • Excellent integration with Spring’s data access abstractions.

Global transactions
Global transactions enable you to work with multiple transactional
resources, typically relational databases and message queues.
The application server manages global transactions through the
JTA, which is a cumbersome API to use (partly due to its exception model).
Local transactions
❖ Local transactions are resource-specific, such as a transaction
associated with a JDBC connection.
❖ Local transactions may be easier to use, but have significant
disadvantages:
❖ They cannot work across multiple transactional resources. For
example, code that manages transactions using a JDBC connection
cannot run within a global JTA transaction. Because the application
server is not involved in transaction management, it cannot help
ensure correctness across multiple resources. (It is worth noting
that most applications use a single transaction resource.)
❖ Another downside is that local transactions are invasive to the
programming model.
Data access with JDBC
You can choose among several approaches to form the basis for your JDBC
database access. In addition to three flavors of the JdbcTemplate, a new
SimpleJdbcInsert and SimplejdbcCall approach optimizes database
metadata, and the RDBMS Object style takes a more object-oriented
approach similar to that of JDO Query design. Once you start using one of
these approaches, you can still mix and match to include a feature from a
different approach. All approaches require a JDBC 2.0-compliant
driver, and some advanced features require a JDBC 3.0 driver.

Package hierarchy
The Spring Framework’s JDBC abstraction framework consists of four
different packages, namely core, datasource, object, and support.

Spring Jdbc
➢ JdbcTemplate is the classic Spring JDBC approach and the most
popular. This is the "lowest level" approach and all others use a
JdbcTemplate under the covers.
➢ NamedParameterJdbcTemplate wraps a JdbcTemplate to
provide named parameters instead of the traditional JDBC "?"
placeholders. This approach provides better documentation
and ease of use when you have multiple parameters for an SQL
statement.
➢ The Spring Framework’s JDBC abstraction framework consists
of four different packages, namely core, datasource, object, and
support.
➢ The org.springframework.jdbc.core package contains the
JdbcTemplate class and its various callback interfaces.
➢ The org.springframework.jdbc.datasource package contains a
utility class for easy DataSource access, and various simple
DataSource implementations that can be used for testing and
running.
➢ The org.springframework.jdbc.object package contains classes
that represent RDBMS queries, updates, and stored procedures
as thread safe, reusable objects.
➢ The org.springframework.jdbc.support package provides
SQLException translation functionality and some utility
classes.
❖ JdbcTemplate
➢ JdbcTemplate class is the central class in the JDBC core
package.
➢ It handles the creation and release of resources.(connection ,
statement ... etc).

❖ NamedParameterJdbcTemplate
❖o The NamedParameterJdbcTemplate class wraps a JdbcTemplate,
and delegates to the wrapped JdbcTemplate to do much of its work.
❖o The NamedParameterJdbcTemplate class adds support for
programming JDBC statements using named parameters, as opposed
to programming JDBC statements using only classic placeholder ( '?')
arguments.

Example :
Hibernate

ØWhat is Hibernate?

ØAdvantages of Hibernate ?
ØWhat ORM does ?
ØHow to save a Java Object with Hibernate?
Ø All the CRUD operations are handled by Hibernate.

Ø What does sessionFactory & session ?

SessionFactory setup in a Spring container


To avoid tying application objects to hard-coded resource lookups,
you can define resources such as a JDBC DataSource or a Hibernate
SessionFactory as beans in the Spring container. Application objects
that need to access resources receive references to such predefined
instances through bean references.

Spring’s LocalSessionFactoryBean supports Hibernate


SessionFactory.getCurrentSession() method for any Spring
transaction strategy, returning the current Spring-managed
transactional Session even with HibernateTransactionManager. Of
of course, the standard behavior of that method remains the return
of the current Session associated with the ongoing JTA transaction.

You annotate the service layer with @Transactional annotations and


instruct the Spring container to find these annotations and provide
transactional semantics for these annotated methods.

All you need to provide is the TransactionManager implementation


and a "<tx:annotation-driven/>" entry.
Refer to the example programme.

The Web
Web MVC framework
❖ The Spring Web model-view-controller (MVC) framework is
designed around a DispatcherServlet that dispatches requests
to handlers, with configurable handler mappings, view
resolution, locale, time zone and theme resolution as well as
support for uploading files.
❖ The default handler is based on the @Controller and
@RequestMapping annotations, offering a wide range of
flexible handling methods.
❖ With the introduction of Spring 3.0, the @Controller
mechanism also allows you to create RESTful Web sites and
applications, through the @PathVariable annotation and other
features.
❖ In Spring Web MVC you can use any object as a command or
form-backing object; you do not need to implement a
framework-specific interface or base class. Spring’s data
binding is highly flexible: example, it treats type mismatches as
validation errors that can be evaluated by the application, not
as system errors. Thus you need not duplicate your business
objects' properties as simple, untyped strings
❖ In your form objects simply to handle invalid submissions, or to
convert the Strings properly. Instead, it is often preferable to
bind directly to your business objects.

Spring’s view resolution is extremely flexible. A Controller is


typically responsible for preparing a model Map with data and
selecting a view name but it can also write directly to the
response stream and complete the request. View name
resolution is highly configurable through file extension
or Accept header content type negotiation, through bean
names, a properties file, or even a custom ViewResolver
implementation. The model (the M in MVC) is a Map interface,
which allows for the complete abstraction of the view
technology. You can integrate directly with template based
rendering technologies such as JSP, Velocity and Freemarker, or
directly generate XML, JSON, Atom, and many other types of
content. The model Map is simply transformed into an
appropriate format, such as JSP request attributes, a Velocity
template model.
Spring’s web module includes many unique web support
features:
❖ Clear separation of roles. Each role—controller, validator,
command object, form object, model object,
DispatcherServlet, handler mapping, view resolver, and
so on—can be fulfilled by a specialized object.
❖ Powerful and straightforward configuration of both
framework and application classes as JavaBeans.
❖ This configuration capability includes easy referencing
across contexts, such as from web controllers
to business objects and validators.
❖ • Adaptability, non-intrusiveness, and flexibility. Define
any controller method signature you need, possibly using
one of the parameter annotations (such as
@RequestParam, @RequestHeader, @PathVariable, and
more) for a given scenario.
❖ Reusable business code, no need for duplication. Use
existing business objects as command or form objects
instead of mirroring them to extend a particula
framework base class.
❖ Customizable binding and validation. Type mismatches
as application-level validation errors that keep
the offending value, localized date and number binding,
and so on instead of String-only form objects
with manual parsing and conversion to business objects.
The DispatcherServlet
Spring’s web MVC framework is, like many other web MVC frameworks,
request-driven, designed around a central Servlet that dispatches requests
to controllers and offers other functionality that facilitates the
development of web applications. Spring’s DispatcherServlet however, does
more
than just that. It is completely integrated with the Spring IoC container
and as such allows you to use every other feature that Spring has.

The DispatcherServlet is an actual Servlet (it inherits from the HttpServlet


base class), and as such is declared in the web.xml of your web application.
You need to map requests that you want the
DispatcherServlet to handle, by using a URL mapping in the same web.xml
file. This is standard Java EE Servlet configuration; the following example
shows such a DispatcherServlet declaration and mapping:
In the preceding example, all requests starting with /example will be
handled by the DispatcherServlet instance named example. In a Servlet
3.0+ environment, you also have the option of configuring the Servlet
container programmatically. Below is the code based equivalent of the
above web.xml example:

WebApplicationInitializer is an interface provided by Spring MVC that


ensures your code-based configuration is detected and automatically used
to initialize any Servlet 3 container. An abstract base class implementation
of this interface named AbstractDispatcherServletInitializer makes it
even easier to register the DispatcherServlet by simply specifying its
servlet mapping.
Upon initialization of a DispatcherServlet, Spring MVC looks for a file
named [servlet-name]- servlet.xml in the WEB-INF directory of your web
application and creates the beans defined there, overriding the definitions
of any beans defined with the same name in the global scope.

Consider the following DispatcherServlet Servlet configuration (in the


web.xml file):
With the above Servlet configuration in place, you will need to have a file
called /WEB-INF/golfing servlet. xml in your application; this file will
contain all of your Spring Web MVC-specific components (beans). You can
change the exact location of this configuration file through a Servlet
initialization
parameter (see below for details).

DispatcherServlet Processing Sequence


After you set up a DispatcherServlet, and a request comes in for that
specific DispatcherServlet, the DispatcherServlet starts processing the
request as follows:

❖ The WebApplicationContext is searched for and bound in the request


as an attribute that the controller and other elements in the process
can use. It is bound by default under the key
DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE.

❖ The locale resolver is bound to the request to enable elements in the


process to resolve the locale to use when processing the request
(rendering the view, preparing data, and so on). If you do not
need locale resolving, you do not need it.
❖ An appropriate handler is searched for. If a handler is found, the
execution chain associated with the handler (preprocessors,
postprocessors, and controllers) is executed in order to prepare a
model or rendering.
❖ Spring 2.5 introduced an annotation-based programming model for
MVC controllers that uses annotations such as @RequestMapping,
@RequestParam, @ModelAttribute, and so on.
❖ This annotation support is available for both Servlet MVC and Portlet
MVC. Controllers implemented in this style do not have to extend
specific base classes or implement specific interfaces. Furthermore,
they do not usually have direct dependencies on Servlet or Portlet
APIs, although you can easily configure access to Servlet or Portlet
facilities.


❖ Defining a controller with @Controller
The @Controller annotation indicates that a particular class serves the
role of a controller. Spring does not require you to extend any controller
base class or reference the Servlet API. However, you can still reference
Servlet-specific features if you need to.
The @Controller annotation acts as a stereotype for the annotated class,
indicating its role. The dispatcher scans such annotated classes for mapped
methods and detects @RequestMapping annotations.

Mapping Requests With @RequestMapping


You use the @RequestMapping annotation to map URLs such as
/appointments onto an entire class or a particular handler method.
Typically the class-level annotation maps a specific request
path (or path pattern) onto a form controller, with additional method-level
annotations narrowing the primary mapping for a specific HTTP method
request method ("GET", "POST", etc.) or an HTTP request parameter
condition.

A method can have any number of @PathVariable annotations:


When a @PathVariable annotation is used on a Map<String, String>
argument, the map is populated with all URI template variables.
A URI template can be assembled from type and path level
@RequestMapping annotations. As a result
the findPet() method can be invoked with a URL such as
/owners/42/pets/21.

Mapping the request body with the @RequestBody annotation


The @RequestBody method parameter annotation indicates that a method
parameter should be bound to the value of the HTTP request body. For
example:

You convert the request body to the method argument by using an


HttpMessageConverter. HttpMessageConverter is responsible for
converting from the HTTP request message to an object
and converting from an object to the HTTP response body. The
RequestMappingHandlerAdapter supports the @RequestBody annotation
with the following default HttpMessageConverters.

Mapping the response body with the @ResponseBody annotation


The @ResponseBody annotation is similar to @RequestBody. This
annotation can be put on a method and indicates that the return type
should be written straight to the HTTP response body (and not placed
in a Model, or interpreted as a view name).
For example:

Creating REST Controllers with the @RestController annotation


It’s a very common use case to have Controllers implement a REST API,
thus serving only JSON, XML or custom MediaType content. For
convenience, instead of annotating all your @RequestMapping
methods with @ResponseBody, you can annotate your Controller Class
with @RestController.
Resolving views
All MVC frameworks for web applications provide a way to address views.
Spring provides view resolvers, which enable you to render models in a
browser without tying you to a specific view technology. Out of the box,
Spring enables you to use JSPs, Velocity templates and XSLT views, for
Example.
The two interfaces that are important to the way Spring handles views are
ViewResolver and View.
The ViewResolver provides a mapping between view names and actual
views. The View interface addresses the preparation of the request and
hands the request over to one of the view technologies.
InternalResourceViewResolver: Convenient subclass of
UrlBasedViewResolver that supports InternalResourceView (in effect,
Servlets and JSPs) and subclasses such as JstlView and TilesView. You can
specify the view class for all views generated by this resolver
by using setViewClass(..). See the UrlBasedViewResolver javadocs for
details.
The Model ModelMap (ModelAndView)
The ModelMap class is essentially a glorified Map that can make adding
objects that are to be displayed in (or on) a View adhere to a common
naming convention. Consider the following Controller implementation;
notice that objects are added to the ModelAndView without any associated
name specified.
The ModelAndView class uses a ModelMap class that is a custom Map
implementation that automatically generates a key for an object when an
object is added to it. The strategy for determining the name for an added
object is, in the case of a scalar object such as User, to use the short class
name of the object’s class. The following examples are names that are
generated for scalar objects put into a ModelMap instance.
Enabling the MVC Java Config or the MVC XML Namespace
To enable MVC Java config add the annotation @EnableWebMvc to one of
your @Configuration classes:
Describe the Front Controller Pattern

In the Front Controller pattern, all requests will first go to the front controller
instead of the servlet. It'll make sure that the responses are ready and will
send them back to the browser. This way we have one place where we control
everything that comes from the outside world.

The front controller will identify the servlet that should handle the request
first. Then, when it gets the data back from the servlet, it'll decide which view
to render and, finally, it'll send the rendered view back as a response:
What Are Model 1 and Model 2 Architectures?

Model 1 and Model 2 represent two frequently used design models when it
comes to designing Java Web Applications.

In Model 1, a request comes to a servlet or JSP where it gets handled. The


servlet or the JSP processes the request, handles business logic, retrieves and
validates data, and generates the response:
ince this architecture is easy to implement, we usually use it in small and
simple applications.

On the other hand, it isn't convenient for large-scale web applications. The
functionalities are often duplicated in JSPs where business and presentation
logic are coupled.

The Model 2 is based on the Model View Controller design pattern and it
separates the view from the logic that manipulates the content.

Furthermore, we can distinguish three modules in the MVC pattern: the


model, the view, and the controller. The model is representing the dynamic
data structure of an application. It's responsible for the data and business
logic manipulation. The view is in charge of displaying the data, while the
controller serves as an interface between the previous two.

In Model 2, a request is passed to the controller, which handles the required


logic in order to get the right content that should be displayed. The controller
then puts the content back into the request, typically as a JavaBean or a POJO.
It also decides which view should render the content and finally passes the
request to it. Then, the view renders the data:

Name the annotations used to handle different types of incoming


HTTP request methods?
The following annotations are used to handle different types of incoming HTTP request methods: -

● @GetMapping

● @PostMapping

● @PutMapping

● @PatchMapping

● @DeleteMapping

What is the purpose of @PathVariable annotation in Spring


MVC?

The @PathVariable annotation is used to extract the value of the URI template. It is passed within the

parameters of the handler method.


For example :-

@RequestMapping("/show/{id}")

public String handler(@PathVariable("id") String s, Model map)

What are the ways of reading data from the form in Spring
MVC?
The following ways to read the data from the form are: -

● HttpServletRequest interface - The HttpServletRequest is a java interface present in

javax.servlet.http package. Like Servlets, you can use HttpServletRequest in Spring to read the

HTML form data provided by the user.

● @RequestParam annotation - The @RequestParam annotation reads the form data and binds it

automatically to the parameter present in the provided method.

● @ModelAttribute annotation - The @ModelAttribute annotation binds a method parameter or

its return value to a named model attribute.

What is Bean Validation API?

The Bean Validation API is a Java specification which is used to apply constraints on object models via

annotations. Here, we can validate a length, number, regular expression, etc. Apart from that, we can

also provide custom validations.


As Bean Validation API is just a specification, it requires an implementation. So, for that, it uses

Hibernate Validator. The Hibernate Validator is a fully compliant JSR-303/309 implementation that

allows to express and validate application constraints.

What is the use of @Valid annotation in Spring MVC?

The @Valid annotation is used to apply validation rules on the provided object.

How to validate a user's input within a number range in Spring


MVC?

In Spring MVC Validation, we can validate the user's input within a number range by using the following

annotations: -

● @Min annotation - It is required to pass an integer value with @Min annotation. The user input

must be equal to or greater than this value.

● @Max annotation - It is required to pass an integer value with @Max annotation. The user input

must be equal to or smaller than this value.

You might also like