AEJP UNIT V

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 34

UNIT - V: SPRING

Spring Framework
Spring is a powerful lightweight application development framework used for Java Enterprise
Edition (JEE). In a way, it is a framework of frameworks because it provides support to various
frameworks such as Struts, Hibernate, Tapestry, EJB, JSF, etc. The framework in a broader sense
can be defined as a structure using which you can solve many technical problems. You can say
that the Spring Framework is a comprehensive tool for supporting applications using Java
programming language.
Roderick B. Johnson, an Australian computer specialist officially released the Spring
Framework in 2004. Since its origin, the Spring Framework has released many versions. 4.3.8 is
the current Spring Framework version.
Features Of Spring Framework
 Lightweight: Spring Framework is lightweight with respect to size and transparency.
 Inversion Of Control (IoC): In Spring Framework, loose coupling is achieved using
Inversion of Control. The objects give their own dependencies instead of creating or
looking for dependent objects.
 Aspect Oriented Programming (AOP): By separating application business logic from
system services, Spring Framework supports Aspect Oriented Programming and enables
cohesive development.
 Container: Spring Framework creates and manages the life cycle and configuration of
application objects.
 MVC Framework: Spring Framework is a MVC web application framework. This
framework is configurable via interfaces and accommodates multiple view technologies.
 Transaction Management: For transaction management, Spring framework provides a
generic abstraction layer. It is not tied to J2EE environments and it can be used in
container-less environments.
 JDBC Exception Handling: The JDBC abstraction layer of the Spring Framework
offers an exception hierarchy, which simplifies the error handling strategy.
Why do we use Spring in Java?
 Works on POJOs (Plain Old Java Object) which makes your application lightweight.
 Provides predefined templates for JDBC, Hibernate, JPA etc., thus reducing your effort
of writing too much code.
 Because of dependency injection feature, your code becomes loosely coupled.
 Using Spring Framework, the development of Java Enterprise
Edition (JEE) applications became faster.
 It also provides strong abstraction to Java Enterprise Edition (JEE) specifications.
 It provides declarative support for transactions, validation, caching and formatting.
But because of having all these advanced features, often people tend to ask questions like,
Is Spring easy to learn?
So let me answer this question in very simple terms. Yes, Java Spring is really easy to learn as
the entire Spring framework is designed to work with POJOs rather than depending on special
interfaces, abstract classes, etc.
So, let’s now dive into this Spring Tutorial, starting off from the very basic differences between
Java and Spring.
What is the difference between Java and Spring?
The below table represents the differences between Java and Spring:
Java Spring
Java is one of the prominent programming Spring is a Java-based open-source application
languages in the market. framework.
Java provides a full-highlighted Enterprise Spring Framework comes with various modules
Application Framework stack called Java EE for like Spring MVC, Spring Boot, Spring Security
which provides various ready to use features for
web application development
web application development.
Java EE is built upon a 3-D Architectural Spring is based on a layered architecture that
Framework which are Logical Tiers, Client consists of various modules that are built on top
Tiers and Presentation Tiers. of its core container.
Since its origin till date, Spring has spread its popularity across various domains. Spring
Framework now is the foundation for various other Spring Projects that have come up in the
offerings in the last two to three years. Check the below image to find out various projects

undertaken by Spring.
Spring Framework Architecture
As you can see in the diagram below, Spring Framework architecture is an arranged layered
architecture that consists of different modules. All the modules have their own functionalities
that are utilized to build an application. There are around 20 modules that are generalized into
Core Container, Data Access/ Integration, Web, AOP (Aspect Oriented Programming),
Instrumentation, and Test. Here, the developer is free to choose the required module. Its
modular architecture enables integration with other frameworks without much hassle.
Let’s now explore these modules in detail. I will start with the Core Container on which the rest
of the modules are constructed, then I’ll talk about Data Access followed by Web and AOP.
Finally, I will discuss some of the miscellaneous modules.

Modules Of Spring Framework


Core Container
This container has the following four modules :
1. Spring Core: This module is the core of the Spring Framework. It provides an
implementation for features like IoC (Inversion of Control) and Dependency Injection
with a singleton design pattern.
2. Spring Bean: This module provides an implementation for the factory design pattern
through BeanFactory.
3. Spring Context: This module is built on the solid base provided by the Core and the
Beans modules and is a medium to access any object defined and configured.
4. Spring Expression Languages (SpEL): This module is an extension to expression
language supported by Java server pages. It provides a powerful expression language for
querying and manipulating an object graph, at runtime.
Spring Data Access/ Integration
It consists of the following five modules:
1. JDBC: This module provides JDBC abstraction layer which eliminates the need of
repetitive and unnecessary exception handling overhead.
2. ORM: ORM stands for Object Relational Mapping. This module provides consistency/
portability to our code regardless of data access technologies based on object oriented
mapping concept.
3. OXM: OXM stands for Object XML Mappers. It is used to convert the objects into XML
format and vice versa. The Spring OXM provides an uniform API to access any of these
OXM frameworks.
4. JMS: JMS stands for Java Messaging Service. This module contains features for
producing and consuming messages among various clients.
5. Transaction: This module supports programmatic and declarative transaction
management for classes that implement special interfaces and for all your POJOs. All the
enterprise level transaction implementation concepts can be implemented in Spring by
using this module.
Spring Web
Web layer includes the following modules:
1. Web: This module using servlet listeners and a web-oriented application context,
provides basic web-oriented integration features like multi-part file upload functionality
and the initialization of the IoC container.
2. Web-Servlet: This module contains Model-View-Controller (MVC) based
implementation for web applications. It provides all other features of MVC, including UI
tags and data validations.
3. Web-Socket: This module provides support for WebSocket based and two-way
communication between the client and the server in web applications.
4. Web-Portlet: This module is also known as the Spring-MVC-Portlet module. It provides
the support for Spring-based Portlets and mirrors the functionality of a Web-Servlet
module.
Aspect-Oriented Programming (AOP)
AOP language is a powerful tool that allows developers to add enterprise functionality to the
application such as transaction, security etc. It allows us to write less code and separate the code
logic. AOP uses cross-cutting concerns.

Spring - Hello World Example

Let us start actual programming with Spring Framework. Before you start writing your first
example using Spring framework, you have to make sure that you have set up your Spring
environment properly as explained in Spring - Environment Setup Chapter. We also assume that
you have a bit of working knowledge on Eclipse IDE.
Now let us proceed to write a simple Spring Application, which will print "Hello World!" or any
other message based on the configuration done in Spring Beans Configuration file.
Step 1 - Create Java Project
The first step is to create a simple Java Project using Eclipse IDE. Follow the option File → New
→ Project and finally select Java Project wizard from the wizard list. Now name your project
as HelloSpring using the wizard window as follows −

Once your project is created successfully, you will have the following content in your Project
Explorer −

Step 2 - Add Required Libraries


As a second step let us add Spring Framework and common logg

ing API libraries in our project. To do


this, right-click on your project name HelloSpring and then follow the following option
available in the context menu − Build Path → Configure Build Path to display the Java Build
Path window as follows −
Now use Add External JARs button available under the Libraries tab to add the following core
JARs from Spring Framework and Common Logging installation directories −
 commons-logging-1.1.1
 spring-aop-4.1.6.RELEASE
 spring-aspects-4.1.6.RELEASE
 spring-beans-4.1.6.RELEASE
 spring-context-4.1.6.RELEASE
 spring-context-support-4.1.6.RELEASE
 spring-core-4.1.6.RELEASE
 spring-expression-4.1.6.RELEASE
 spring-instrument-4.1.6.RELEASE
 spring-instrument-tomcat-4.1.6.RELEASE
 spring-jdbc-4.1.6.RELEASE
 spring-jms-4.1.6.RELEASE
 spring-messaging-4.1.6.RELEASE
 spring-orm-4.1.6.RELEASE
 spring-oxm-4.1.6.RELEASE
 spring-test-4.1.6.RELEASE
 spring-tx-4.1.6.RELEASE
 spring-web-4.1.6.RELEASE
 spring-webmvc-4.1.6.RELEASE
 spring-webmvc-portlet-4.1.6.RELEASE
 spring-websocket-4.1.6.RELEASE
Step 3 - Create Source Files
Now let us create actual source files under the HelloSpring project. First we need to create a
package called com.tutorialspoint. To do this, right click on src in package explorer section and
follow the option − New → Package.
Next we will create HelloWorld.java and MainApp.java files under the com.tutorialspoint
package.

Here is the content of HelloWorld.java file −


package com.tutorialspoint;

public class HelloWorld {


private String message;

public void setMessage(String message){


this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
Following is the content of the second file MainApp.java −
package com.tutorialspoint;

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

public class MainApp {


public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
}
}
Following two important points are to be noted about the main program −
 The first step is to create an application context where we used framework API
ClassPathXmlApplicationContext(). This API loads beans configuration file and
eventually based on the provided API, it takes care of creating and initializing all the
objects, i.e. beans mentioned in the configuration file.
 The second step is used to get the required bean using getBean() method of the created
context. This method uses bean ID to return a generic object, which finally can be casted
to the actual object. Once you have an object, you can use this object to call any class
method.
Step 4 - Create Bean Configuration File
You need to create a Bean Configuration file which is an XML file and acts as a cement that
glues the beans, i.e. the classes together. This file needs to be created under the src directory as
shown in the following screenshot −

Usually developers name this file as Beans.xml, but you are independent to choose any name
you like. You have to make sure that this file is available in CLASSPATH and use the same
name in the main application while creating an application context as shown in MainApp.java
file.
The Beans.xml is used to assign unique IDs to different beans and to control the creation of
objects with different values without impacting any of the Spring source files. For example,
using the following file you can pass any value for "message" variable and you can print
different values of message without impacting HelloWorld.java and MainApp.java files. Let us
see how it works −
<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"


xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld">


<property name = "message" value = "Hello World!"/>
</bean>

</beans>
When Spring application gets loaded into the memory, Framework makes use of the above
configuration file to create all the beans defined and assigns them a unique ID as defined in
<bean> tag. You can use <property> tag to pass the values of different variables used at the
time of object creation.
Step 5 - Running the Program
Once you are done with creating the source and beans configuration files, you are ready for this
step, which is compiling and running your program. To do this, keep MainApp.Java file tab
active and use either Run option available in the Eclipse IDE or use Ctrl + F11 to compile and
run your MainApp application. If everything is fine with your application, this will print the
following message in Eclipse IDE's console −
Your Message : Hello World!
Congratulations, you have successfully created your first Spring Application. You can see the
flexibility of the above Spring application by changing the value of "message" property and
keeping both the source files unchanged.

Spring - Dependency Injection

Every Java-based application has a few objects that work together to present what the
end-user sees as a working application. When writing a complex Java application, application
classes should be as independent as possible of other Java classes to increase the possibility to
reuse these classes and to test them independently of other classes while unit testing.
Dependency Injection (or sometime called wiring) helps in gluing these classes together and at
the same time keeping them independent.
Consider you have an application which has a text editor component and you want to provide a
spell check. Your standard code would look something like this −
public class TextEditor {
private SpellChecker spellChecker;

public TextEditor() {
spellChecker = new SpellChecker();
}
}
What we've done here is, create a dependency between the TextEditor and the SpellChecker. In
an inversion of control scenario, we would instead do something like this −
public class TextEditor {
private SpellChecker spellChecker;

public TextEditor(SpellChecker spellChecker) {


this.spellChecker = spellChecker;
}
}
Here, the TextEditor should not worry about SpellChecker implementation. The SpellChecker
will be implemented independently and will be provided to the TextEditor at the time of
TextEditor instantiation. This entire procedure is controlled by the Spring Framework.
Here, we have removed total control from the TextEditor and kept it somewhere else (i.e. XML
configuration file) and the dependency (i.e. class SpellChecker) is being injected into the class
TextEditor through a Class Constructor. Thus the flow of control has been "inverted" by
Dependency Injection (DI) because you have effectively delegated dependances to some external
system.
The second method of injecting dependency is through Setter Methods of the TextEditor class
where we will create a SpellChecker instance. This instance will be used to call setter methods to
initialize TextEditor's properties.
Thus, DI exists in two major variants and the following two sub-chapters will cover both of them
with examples −
Sr.No. Dependency Injection Type & Description
Constructor-based dependency injection
1 Constructor-based DI is accomplished when the container invokes a class constructor with
a number of arguments, each representing a dependency on the other class.
Setter-based dependency injection
Setter-based DI is accomplished by the container calling setter methods on your beans
2
after invoking a no-argument constructor or no-argument static factory method to
instantiate your bean.
You can mix both, Constructor-based and Setter-based DI but it is a good rule of thumb to use
constructor arguments for mandatory dependencies and setters for optional dependencies.
The code is cleaner with the DI principle and decoupling is more effective when objects are
provided with their dependencies. The object does not look up its dependencies and does not
know the location or class of the dependencies, rather everything is taken care by the Spring
Framework.
Spring – Understanding Inversion of Control with Example
 Last Updated : 18 Feb, 2022
Spring IoC (Inversion of Control) Container is the core of Spring Framework. It creates the
objects, configures and assembles their dependencies, manages their entire life cycle. The
Container uses Dependency Injection(DI) to manage the components that make up the
application. It gets the information about the objects from a configuration file(XML) or Java
Code or Java Annotations and Java POJO class. These objects are called Beans. Since the
Controlling of Java objects and their lifecycle is not done by the developers, hence the name
Inversion Of Control.
There are 2 types of IoC containers:
 BeanFactory
 ApplicationContext
That means if you want to use an IoC container in spring whether we need to use a BeanFactory
or ApplicationContext. The BeanFactory is the most basic version of IoC containers, and the
ApplicationContext extends the features of BeanFactory. The followings are some of the main
features of Spring IoC,
 Creating Object for us,
 Managing our objects,
 Helping our application to be configurable,
 Managing dependencies
Implementation: So now let’s understand what is IoC in Spring with an example. Suppose we
have one interface named Sim and it has some abstract methods calling() and data().
// Java Program to Illustrate Sim Interface
public interface Sim
{
void calling();
void data();
}
Now we have created another two classes Airtel and Jio which implement the Sim interface and
override the interface methods.
// Java Program to Illustrate Airtel Class
// Class
// Implementing Sim interface
public class Airtel implements Sim {

@Override public void calling()


{
System.out.println("Airtel Calling");
}

@Override public void data()


{
System.out.println("Airtel Data");
}
}
// Java Program to Illustrate Jio Class

// Class
// Implementing Sim interface
public class Jio implements Sim{
@Override
public void calling() {
System.out.println("Jio Calling");
}

@Override
public void data() {
System.out.println("Jio Data");
}
}

So let’s now call these methods inside the main method. So by implementing the Run time
polymorphism concept we can do something like this
// Java Program to Illustrate Mobile Class

// Class
public class Mobile {

// Main driver method


public static void main(String[] args)
{

// Creating instance of Sim interface


// inside main() method
// with reference to Jio class constructor
// invocation
Sim sim = new Jio();

// Sim sim = new Airtel();

sim.calling();
sim.data();
}
}

But what happens if in the future another new Sim Vodafone came and we need to change again
to the child class name in the code, like this
Sim sim = new Vodafone();
So we have to do our configuration in the source code. So how to make it configurable? We
don’t want to touch the source code of this. The source code should be constant. And how can
we make it? Here Spring IoC comes into the picture. So in this example, we are going to use
ApplicationContext to implement an IoC container. First, we have to create an XML file and
name the file as “beans.xml“.
Example: beans.xml File
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="sim" class="Jio"></bean>

</beans>

Output Explanation: In the beans.xml file, we have created beans. So inside the id, we have to
pass the unique id and inside the class, we have to pass the Class name for which you want to
create the bean. Later on, inside the main method, we can tweek it out that will be described in
the upcoming program.
Bean Definition: In Spring, the objects that form the backbone of your application and that are
managed by the Spring IoC container are called beans. A bean is an object that is instantiated,
assembled, and otherwise managed by a Spring IoC container.
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Mobile {


public static void main(String[] args) {
// Using ApplicationContext tom implement Spring IoC
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("beans.xml");

// Get the bean


Sim sim = applicationContext.getBean("sim", Sim.class);

// Calling the methods


sim.calling();
sim.data();
}
}
Output:
Jio Calling
Jio Data
And now if you want to use the Airtel sim so you have to change only inside the beans.xml file.
The main method is going to be the same.
<bean id="sim" class="Airtel"></bean>
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Mobile {


public static void main(String[] args) {

// Using ApplicationContext tom implement Spring IoC


ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("beans.xml");

// Get the bean


Sim sim = applicationContext.getBean("sim", Sim.class);

// Calling the methods


sim.calling();
sim.data();
}
}
Output:
Airtel Calling
Airtel Data
Spring - IoC Containers
The Spring container is at the core of the Spring Framework. The container will create
the objects, wire them together, configure them, and manage their complete life cycle from
creation till destruction. The Spring container uses DI to manage the components that make up
an application. These objects are called Spring Beans, which we will discuss in the next chapter.
The container gets its instructions on what objects to instantiate, configure, and assemble by
reading the configuration metadata provided. The configuration metadata can be represented
either by XML, Java annotations, or Java code. The following diagram represents a high-level
view of how Spring works. The Spring IoC container makes use of Java POJO classes and
configuration metadata to produce a fully configured and executable system or application.

Spring provides the following two distinct types of containers.


Sr.No. Container & Description
1 Spring BeanFactory Container
This is the simplest container providing the basic support for DI and is defined by the
org.springframework.beans.factory.BeanFactory interface. The BeanFactory and related
interfaces, such as BeanFactoryAware, InitializingBean, DisposableBean, are still present
in Spring for the purpose of backward compatibility with a large number of third-party
frameworks that integrate with Spring.
Spring ApplicationContext Container
This container adds more enterprise-specific functionality such as the ability to resolve
2 textual messages from a properties file and the ability to publish application events to
interested event listeners. This container is defined by the
org.springframework.context.ApplicationContext interface.
The ApplicationContext container includes all functionality of the BeanFactorycontainer, so it is
generally recommended over BeanFactory. BeanFactory can still be used for lightweight
applications like mobile devices or applet-based applications where data volume and speed is
significant.
Introduction to Spring Framework
 Difficulty Level : Medium
 Last Updated : 05 Dec, 2019
Introduction
Prior to the advent of Enterprise Java Beans (EJB), Java developers needed to use JavaBeans to
create Web applications. Although JavaBeans helped in the development of user interface (UI)
components, they were not able to provide services, such as transaction management and
security, which were required for developing robust and secure enterprise applications. The
advent of EJB was seen as a solution to this problem EJB extends the Java components, such as
Web and enterprise components, and provides services that help in enterprise application
development. However, developing an enterprise application with EJB was not easy, as the
developer needed to perform various tasks, such as creating Home and Remote interfaces and
implementing lifecycle callback methods which lead to the complexity of providing code for
EJBs Due to this complication, developers started looking for an easier way to develop enterprise
applications.
The Spring framework has emerged as a solution to all these complications This framework uses
various new techniques such as Aspect-Oriented Programming (AOP), Plain Old Java Object
(POJO), and dependency injection (DI), to develop enterprise applications, thereby removing the
complexities involved while developing enterprise applications using EJB, Spring is an open
source lightweight framework that allows Java EE 7 developers to build simple, reliable, and
scalable enterprise applications. This framework mainly focuses on providing various ways to
help you manage your business objects. It made the development of Web applications much
easier as compared to classic Java frameworks and Application Programming Interfaces (APIs),
such as Java database connectivity(JDBC), JavaServer Pages(JSP), and Java Servlet.
The Spring framework can be considered as a collection of sub-frameworks, also called layers,
such as Spring AOP. Spring Object-Relational Mapping (Spring ORM). Spring Web Flow, and
Spring Web MVC. You can use any of these modules separately while constructing a Web
application. The modules may also be grouped together to provide better functionalities in a Web
application.
Features of the Spring Framework
The features of the Spring framework such as IoC, AOP, and transaction management, make it
unique among the list of frameworks. Some of the most important features of the Spring
framework are as follows:
 IoC container:
Refers to the core container that uses the DI or IoC pattern to implicitly provide an object
reference in a class during runtime. This pattern acts as an alternative to the service
locator pattern. The IoC container contains assembler code that handles the configuration
management of application objects.
The Spring framework provides two packages, namely org.springframework.beans and
org.springframework.context which helps in providing the functionality of the IoC
container.
 Data access framework:
Allows the developers to use persistence APIs, such as JDBC and Hibernate, for storing
persistence data in database. It helps in solving various problems of the developer, such
as how to interact with a database connection, how to make sure that the connection is
closed, how to deal with exceptions, and how to implement transaction management It
also enables the developers to easily write code to access the persistence data throughout
the application.
 Spring MVC framework:
Allows you to build Web applications based on MVC architecture. All the requests made
by a user first go through the controller and are then dispatched to different views, that is,
to different JSP pages or Servlets. The form handling and form validating features of the
Spring MVC framework can be easily integrated with all popular view technologies such
as ISP, Jasper Report, FreeMarker, and Velocity.
 Transaction management:
Helps in handling transaction management of an application without affecting its code.
This framework provides Java Transaction API (JTA) for global transactions managed by
an application server and local transactions managed by using the JDBC Hibernate, Java
Data Objects (JDO), or other data access APIs. It enables the developer to model a wide
range of transactions on the basis of Spring’s declarative and programmatic transaction
management.
 Spring Web Service:
Generates Web service endpoints and definitions based on Java classes, but it is difficult
to manage them in an application. To solve this problem, Spring Web Service provides
layered-based approaches that are separately managed by Extensible Markup Language
(XML) parsing (the technique of reading and manipulating XML). Spring provides
effective mapping for transmitting incoming XML message request to an object and the
developer to easily distribute XML message (object) between two machines.
 JDBC abstraction layer:
Helps the users in handling errors in an easy and efficient manner. The JDBC
programming code can be reduced when this abstraction layer is implemented in a Web
application. This layer handles exceptions such as DriverNotFound. All SQLExceptions
are translated into the DataAccessException class. Spring’s data access exception is not
JDBC specific and hence Data Access Objects (DAO) are not bound to JDBC only.
 Spring TestContext framework:
Provides facilities of unit and integration testing for the Spring applications. Moreover,
the Spring TestContext framework provides specific integration testing functionalities
such as context management and caching DI of test fixtures, and transactional test
management with default rollback semantics.
Evolution of Spring Framework
The Spring Framework was first released in 2004. After that there has been a significant
major revision, such as Spring 2.0 provided XML namespaces and AspectJ support, Spring 2.5
provide annotation-driven configuration, Spring 3.0 provided a Java-based @Configuration
model. The latest release of the spring framework is 4.0. it is released with the support for Java 8
and Java EE 7 technologies. Though you can still use Spring with an older version of java, the
minimum requirement is restricted to Java SE 6. Spring 4.0 also supports Java EE 7
technologies, such as java message service (JMS) 2.0, java persistence API (JPA) 2.1, Bean
validation 1.1, servlet 3.1, and JCache.
Spring Framework Architecture

The Spring framework consists of seven modules which are shown in the above Figure. These
modules are Spring Core, Spring AOP, Spring Web MVC, Spring DAO, Spring ORM, Spring
context, and Spring Web flow. These modules provide different platforms to develop different
enterprise applications; for example, you can use Spring Web MVC module for developing
MVC-based applications.
Spring Framework Modules
 Spring Core Module:
The Spring Core module, which is the core component of the Spring framework, provides
the IoC container There are two types of implementations of the Spring container,
namely, bean factory and application context. Bean factory is defined using the
org.springframework.beans.factory.BeanFactory interface and acts as a container for
beans. The Bean factory container allows you to decouple the configuration and
specification of dependencies from program logic. In the Spring framework, the Bean
factory acts as a central IoC container that is responsible for instantiating application
objects. It also configures and assembles the dependencies between these objects. There
are numerous implementations of the BeanFactory interface. The XmlBeanFactory class
is the most common implementation of the BeanFactory interface. This allows you to
express the object to compose your application and remove interdependencies between
application objects.
 Spring AOP Module:
Similar to Object-Oriented Programming (OOP), which breaks down the applications
into hierarchy of objects, AOP breaks down the programs into aspects or concerns.
Spring AOP module allows you to implement concerns or aspects in a Spring application
in Spring AOP, the aspects are the regular Spring beans or regular classes annotated with
@Aspect annotation. These aspects help in transaction management and logging and
failure monitoring of an application. For example, transaction management is required in
bank operations such as transferring an amount from one account to another Spring AOP
module provides a transaction management abstraction layer that can be applied to
transaction APIs.
 Spring ORM Module:
The Spring ORM module is used for accessing data from databases in an application. It
provides APIs for manipulating databases with JDO, Hibernate, and iBatis. Spring ORM
supports DAO, which provides a convenient way to build the following DAOs-based
ORM solutions:
o Simple declarative transaction management
o Transparent exception handling
o Thread-safe, lightweight template classes
o DAO support classes
o Resource management
 Spring Web MVC Module:
The Web MVC module of Spring implements the MVC architecture for creating Web
applications. It separates the code of model and view components of a Web application.
In Spring MVC, when a request is generated from the browser, it first goes to the
DispatcherServlet class (Front Controller), which dispatches the request to a controller
(SimpleFormController class or AbstractWizardformController class) using a set of
handler mappings. The controller extracts and processes the information embedded in a
request and sends the result to the DispatcherServlet class in the form of the model
object. Finally, the DispatcherServlet class uses ViewResolver classes to send the results
to a view, which displays these results to the users.
 Spring Web Flow Module:
The Spring Web Flow module is an extension of the Spring Web MVC module. Spring
Web MVC framework provides form controllers, such as class SimpleFormController
and AbstractWizardFormController class, to implement predefined workflow. The Spring
Web Flow helps in defining XML file or Java Class that manages the workflow between
different pages of a Web application. The Spring Web Flow is distributed separately and
can be downloaded through http://www.springframework.org website.
The following are the advantages of Spring Web Flow:
o The flow between different UIs of the application is clearly provided by defining
Web flow in XML file.
o Web flow definitions help you to virtually split an application in different
modules and reuse these modules in multiple situations.
Spring Web Flow lifecycle can be managed automatically
 Spring Web DAO Module:
The DAO package in the Spring framework provides DAO support by using data access
technologies such as JDBC, Hibernate, or JDO. This module introduces a JDBC
abstraction layer by eliminating the need for providing tedious JDBC coding. It also
provides programmatic as well as declarative transaction management classes. Spring
DAO package supports heterogeneous Java Database Connectivity and O/R mapping,
which helps Spring work with several data access technologies. For easy and quick
access to database resources, the Spring framework provides abstract DAO base classes.
Multiple implementations are available for each data access technology supported by the
Spring framework. For example, in JDBC, the JdbcDaoSupport class and its methods are
used to access the DataSource instance and a preconfigured JdbcTemplate instance. You
need to simply extend the JdbcDaoSupport class and provide a mapping to the actual
DataSource instance in an application context configuration to access a DAO-based
application.
 Spring Application Context Module:
The Spring Application context module is based on the Core module. Application context
org.springframework.context.ApplicationContext is an interface of BeanFactory. This
module derives its feature from the org.springframework.beans package and also supports
functionalities such as internationalization (I18N), validation, event propagation, and
resource loading. The Application context implements MessageSource interface and
provides the messaging functionality to an application.
Spring - Bean Definition
The objects that form the backbone of your application and that are managed by the
Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and
otherwise managed by a Spring IoC container. These beans are created with the configuration
metadata that you supply to the container. For example, in the form of XML <bean/> definitions
which you have already seen in the previous chapters.
Bean definition contains the information called configuration metadata, which is needed for the
container to know the following −
 How to create a bean
 Bean's lifecycle details
 Bean's dependencies
All the above configuration metadata translates into a set of the following properties that make
up each bean definition.
Sr.No. Properties & Description
class
1
This attribute is mandatory and specifies the bean class to be used to create the bean.
name
2 This attribute specifies the bean identifier uniquely. In XMLbased configuration metadata,
you use the id and/or name attributes to specify the bean identifier(s).
scope
3 This attribute specifies the scope of the objects created from a particular bean definition
and it will be discussed in bean scopes chapter.
constructor-arg
4
This is used to inject the dependencies and will be discussed in subsequent chapters.
properties
5
This is used to inject the dependencies and will be discussed in subsequent chapters.
autowiring mode
6
This is used to inject the dependencies and will be discussed in subsequent chapters.
lazy-initialization mode
7 A lazy-initialized bean tells the IoC container to create a bean instance when it is first
requested, rather than at the startup.
initialization method
8 A callback to be called just after all necessary properties on the bean have been set by the
container. It will be discussed in bean life cycle chapter.
destruction method
9 A callback to be used when the container containing the bean is destroyed. It will be
discussed in bean life cycle chapter.
Spring Configuration Metadata
Spring IoC container is totally decoupled from the format in which this configuration metadata is
actually written. Following are the three important methods to provide configuration metadata to
the Spring Container −
 XML based configuration file.
 Annotation-based configuration
 Java-based configuration
You already have seen how XML-based configuration metadata is provided to the container, but
let us see another sample of XML-based configuration file with different bean definitions
including lazy initialization, initialization method, and destruction method −
<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"


xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<!-- A simple bean definition -->


<bean id = "..." class = "...">
<!-- collaborators and configuration for this bean go here -->
</bean>

<!-- A bean definition with lazy init set on -->


<bean id = "..." class = "..." lazy-init = "true">
<!-- collaborators and configuration for this bean go here -->
</bean>

<!-- A bean definition with initialization method -->


<bean id = "..." class = "..." init-method = "...">
<!-- collaborators and configuration for this bean go here -->
</bean>

<!-- A bean definition with destruction method -->


<bean id = "..." class = "..." destroy-method = "...">
<!-- collaborators and configuration for this bean go here -->
</bean>

<!-- more bean definitions go here -->

</beans>
You can check Spring Hello World Example to understand how to define, configure and create
Spring Beans.
We will discuss about Annotation Based Configuration in a separate chapter. It is intentionally
discussed in a separate chapter as we want you to grasp a few other important Spring concepts,
before you start programming with Spring Dependency Injection with Annotations.
Naming Spring Beans

1. Overview
In this article, we'll look at how we can name our Spring beans. By controlling the naming of our
beans, we can tell Spring which beans we want to inject into a target bean.
2. Default Bean Naming Strategy
Let's start with the default bean naming strategy employed by Spring.
Spring gets the class name and converts the first letter to lowercase. Then, this value
becomes the name of the bean.
We'll use the AuditService interface for the upcoming examples:
public interface AuditService {
}
Now, let's see the default name generated for an AuditService implementation:
@Component
public class LegacyAuditService implements AuditService {
}
Here, we have the LegacyAuditService bean. Spring will register this bean under the name of
legacyAuditService.
3. Naming Beans using @Component
Now, let's look at how we can name our beans using the @Component annotation.
We can define the bean name using the value of @Component:
@Component("advanced")
public class AdvancedAuditService implements AuditService {
}
Here, Spring will register the AdvancedAuditService under the name of advanced.
4. Naming Beans using @Qualifier
Another way to name our Spring beans is by using the @Qualifier annotation.
Similar to @Component, we can use the value of @Qualifier to define a name. Moreover, we
can use both approaches at the same time:
@Component("advanced")
@Qualifier("qualifiedAdvanced")
public class AdvancedAuditService implements AuditService {
}
Here, Spring will register the AdvancedAuditService bean under two different names: advanced
and qualifiedAdvanced.
5. Using @Bean
There are also several approaches for naming the beans defined with the @Bean annotation.
5.1. Naming Beans with @Bean
Firstly, we can use the value of @Bean to name our beans:
public class SimpleAuditService implements AuditService{
}
Here is our SimpleAuditService class. Let's look at the bean configuration:
@Configuration
public class AuditConfiguration {

@Bean("simple")
public AuditService theSimpleOne() {
return new SimpleAuditService();
}
}
Here Spring will register SimpleAuditService under the name of simple.
5.2. Naming Beans with @Qualifier and @Bean
Secondly, we can use the @Qualifier annotation with @Bean methods to name our beans.
Moreover, we can also combine two approaches:
@Configuration
public class AuditConfiguration {

@Bean("simple")
@Qualifier("qualifiedSimple")
public AuditService theSimpleOne() {
return new SimpleAuditService();
}
}
As a result, Spring will register the SimpleAuditService bean under two names: simple and
qualifiedSimple.
5.3. Naming Beans with Method Name
Lastly, we can name our beans using the @Bean method name:
public class ObsoleteAuditService implements AuditService {
}
Here we have the ObsoleteAuditService class.
We'll look at the configuration next:
package com.javabyexamples.spring.core.beannaming;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AuditConfiguration {

@Bean
public AuditService obsolete(){
return new LegacyAuditService();
}
}
Since we aren't specifying a name in the @Bean annotation, Spring uses the method name,
obsolete, as the name of the bean.
Spring - Bean Scopes
When defining a <bean> you have the option of declaring a scope for that bean. For example, to
force Spring to produce a new bean instance each time one is needed, you should declare the
bean's scope attribute to be prototype. Similarly, if you want Spring to return the same bean
instance each time one is needed, you should declare the bean's scope attribute to be singleton.
The Spring Framework supports the following five scopes, three of which are available only if
you use a web-aware ApplicationContext.
Sr.No. Scope & Description
singleton
1
This scopes the bean definition to a single instance per Spring IoC container (default).
prototype
2
This scopes a single bean definition to have any number of object instances.
request
3 This scopes a bean definition to an HTTP request. Only valid in the context of a web-
aware Spring ApplicationContext.
session
4 This scopes a bean definition to an HTTP session. Only valid in the context of a web-
aware Spring ApplicationContext.
global-session
5 This scopes a bean definition to a global HTTP session. Only valid in the context of a
web-aware Spring ApplicationContext.
In this chapter, we will discuss about the first two scopes and the remaining three will be
discussed when we discuss about web-aware Spring ApplicationContext.
The singleton scope
If a scope is set to singleton, the Spring IoC container creates exactly one instance of the object
defined by that bean definition. This single instance is stored in a cache of such singleton beans,
and all subsequent requests and references for that named bean return the cached object.
The default scope is always singleton. However, when you need one and only one instance of a
bean, you can set the scope property to singleton in the bean configuration file, as shown in the
following code snippet −
<!-- A bean definition with singleton scope -->
<bean id = "..." class = "..." scope = "singleton">
<!-- collaborators and configuration for this bean go here -->
</bean>
Example
Let us have a working Eclipse IDE in place and take the following steps to create a Spring
application −
Steps Description
Create a project with a name SpringExample and create a package com.tutorialspoint under
1
the src folder in the created project.
Add required Spring libraries using Add External JARs option as explained in the Spring
2
Hello World Example chapter.
3 Create Java classes HelloWorld and MainApp under the com.tutorialspoint package.
4 Create Beans configuration file Beans.xml under the src folder.
The final step is to create the content of all the Java files and Bean Configuration file and
5
run the application as explained below.
Here is the content of HelloWorld.java file −
package com.tutorialspoint;

public class HelloWorld {


private String message;

public void setMessage(String message){


this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
Following is the content of the MainApp.java file −
package com.tutorialspoint;

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

public class MainApp {


public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld objA = (HelloWorld) context.getBean("helloWorld");

objA.setMessage("I'm object A");


objA.getMessage();

HelloWorld objB = (HelloWorld) context.getBean("helloWorld");


objB.getMessage();
}
}
Following is the configuration file Beans.xml required for singleton scope −
<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"


xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld" scope = "singleton">


</bean>

</beans>
Once you are done creating the source and bean configuration files, let us run the application. If
everything is fine with your application, it will print the following message −
Your Message : I'm object A
Your Message : I'm object A
The prototype scope
If the scope is set to prototype, the Spring IoC container creates a new bean instance of the object
every time a request for that specific bean is made. As a rule, use the prototype scope for all
state-full beans and the singleton scope for stateless beans.
To define a prototype scope, you can set the scope property to prototype in the bean
configuration file, as shown in the following code snippet −
<!-- A bean definition with prototype scope -->
<bean id = "..." class = "..." scope = "prototype">
<!-- collaborators and configuration for this bean go here -->
</bean>
Example
Let us have working Eclipse IDE in place and follow the following steps to create a Spring
application −
Steps Description
Create a project with a name SpringExample and create a package com.tutorialspoint under
1
the src folder in the created project.
Add required Spring libraries using Add External JARs option as explained in the Spring
2
Hello World Example chapter.
3 Create Java classes HelloWorld and MainApp under the com.tutorialspoint package.
4 Create Beans configuration file Beans.xml under the src folder.
The final step is to create the content of all the Java files and Bean Configuration file and
5
run the application as explained below.
Here is the content of HelloWorld.java file
package com.tutorialspoint;

public class HelloWorld {


private String message;

public void setMessage(String message){


this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
Following is the content of the MainApp.java file −
package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld objA = (HelloWorld) context.getBean("helloWorld");

objA.setMessage("I'm object A");


objA.getMessage();

HelloWorld objB = (HelloWorld) context.getBean("helloWorld");


objB.getMessage();
}
}
Following is the configuration file Beans.xml required for prototype scope −
<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"


xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld" scope = "prototype">


</bean>

</beans>
Once you are done creating the source and bean configuration files, let us run the application. If
everything is fine with your application, it will print the following message −
Your Message : I'm object A
Your Message : null
Spring Bean Reference ,<ref> Tag in Spring

In Spring if one Bean depends on another Bean class for some business logic, then this
type of dependency is called object dependency.In case of Object dependency in Spring, the
spring IOC container is responsible for creating that required object and injecting into the
dependent classes.

In Spring we need to use <ref> element to inform spring container about the object dependency.

In Spring, beans can "access" to each other by specify the bean references in the same or
different bean configuration file.In spring we can write multiple configuration xml file.Our
associated bean may be in same xml or in other xml file.

Beans defined in different XML files


If you are trying to access bean from different XML file, then we need to use ‘ref‘ tag with
‘bean‘ attribute.

Syntax :
<ref bean="someBean"/>
Consider the xml file given below.
account-bean.xml
?
1<?xml version="1.0" encoding="UTF-8"?>
2<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3
xsi:schemaLocation="http://www.springframework.org/schema/beans
4
http://www.springframework.org/schema/beans/spring-beans.xsd">
5
6
<bean id="accountDetails" class="com.jwt.spring.AccountImpl"/>
7
8
</beans>
In the above xml file AccountImpl bean is configured.
Now in the below xml file we are referring ,”accountDetails” configured in the
account=bean.xml file, so we need to use ‘ref‘ tag with ‘bean‘ attribute i.e <ref
bean=”accountDetails”/>.
bank-bean.xml
?
1
2
<?xml version="1.0" encoding="UTF-8"?>
3
<beans xmlns="http://www.springframework.org/schema/beans"
4
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5
xsi:schemaLocation="http://www.springframework.org/schema/beans
6
http://www.springframework.org/schema/beans/spring-beans.xsd">
7
8
9
<bean id="bankservice" class="com.jwt.spring.BankService">
1
<property name="accdetails">
0
<ref bean="accountDetails"/>
1
</property>
1
</bean>
1
2
</beans>
1
3

Bean defined in same XML file


If you are referring to a bean in same XML file, you can reference it with ‘ref‘ tag, and ‘local‘
attribute.
Syntax :
<ref local=”referencebean”/>
In the below xml file,”accountDetails” is configured in the same beans.xml so we need to use
‘ref‘ tag with ‘local‘ attribute.
Beans.xml
?
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://www.springframework.org/schema/beans
5 http://www.springframework.org/schema/beans/spring-beans.xsd">
6
7 <bean id="accountDetails" class="com.jwt.spring.AccountImpl"/>
8 <bean id="bankservice" class="com.jwt.spring.BankService">
9 <property name="accdetails">
1 <ref local="accountDetails"/>
0 </property>
1 </bean>
1
1
2
</beans>
1
3
JavaBeans Properties
A JavaBean property is a named attribute that can be accessed by the user of the object.
The attribute can be of any Java data type, including the classes that you define.
A JavaBean property may be read, write, read only, or write only. JavaBean properties are
accessed through two methods in the JavaBean's implementation class −
S.No. Method & Description
getPropertyName()
1 For example, if property name is firstName, your method name would be
getFirstName() to read that property. This method is called accessor.
setPropertyName()
2 For example, if property name is firstName, your method name would be
setFirstName() to write that property. This method is called mutator.
A read-only attribute will have only a getPropertyName() method, and a write-only attribute
will have only a setPropertyName() method.
JavaBeans Example
Consider a student class with few properties −
package com.tutorialspoint;

public class StudentsBean implements java.io.Serializable {


private String firstName = null;
private String lastName = null;
private int age = 0;

public StudentsBean() {
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public int getAge(){
return age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(Integer age){
this.age = age;
}
}
Accessing JavaBeans
The useBean action declares a JavaBean for use in a JSP. Once declared, the bean becomes a
scripting variable that can be accessed by both scripting elements and other custom tags used in
the JSP. The full syntax for the useBean tag is as follows −
<jsp:useBean id = "bean's name" scope = "bean's scope" typeSpec/>
Here values for the scope attribute can be a page, request, session or application based on your
requirement. The value of the id attribute may be any value as a long as it is a unique name
among other useBean declarations in the same JSP.
Following example shows how to use the useBean action −
<html>
<head>
<title>useBean Example</title>
</head>

<body>
<jsp:useBean id = "date" class = "java.util.Date" />
<p>The date/time is <%= date %>
</body>
</html>
You will receive the following result − −
The date/time is Thu Sep 30 11:18:11 GST 2010
Accessing JavaBeans Properties
Along with <jsp:useBean...> action, you can use the <jsp:getProperty/> action to access the
get methods and the <jsp:setProperty/> action to access the set methods. Here is the full syntax

<jsp:useBean id = "id" class = "bean's class" scope = "bean's scope">
<jsp:setProperty name = "bean's id" property = "property name"
value = "value"/>
<jsp:getProperty name = "bean's id" property = "property name"/>
...........
</jsp:useBean>
The name attribute references the id of a JavaBean previously introduced to the JSP by the
useBean action. The property attribute is the name of the get or the set methods that should be
invoked.
Following example shows how to access the data using the above syntax −
<html>
<head>
<title>get and set properties Example</title>
</head>

<body>
<jsp:useBean id = "students" class = "com.tutorialspoint.StudentsBean">
<jsp:setProperty name = "students" property = "firstName" value = "Zara"/>
<jsp:setProperty name = "students" property = "lastName" value = "Ali"/>
<jsp:setProperty name = "students" property = "age" value = "10"/>
</jsp:useBean>

<p>Student First Name:


<jsp:getProperty name = "students" property = "firstName"/>
</p>

<p>Student Last Name:


<jsp:getProperty name = "students" property = "lastName"/>
</p>

<p>Student Age:
<jsp:getProperty name = "students" property = "age"/>
</p>

</body>
</html>
Let us make the StudentsBean.class available in CLASSPATH. Access the above JSP. the
following result will be displayed −
Student First Name: Zara

Student Last Name: Ali

Student Age: 10
Resources
1 Introduction
Java's standard java.net.URL class and standard handlers for various URL prefixes unfortunately
are not quite adequate enough for all access to low-level resources. For example, there is no
standardized URL implementation that may be used to access a resource that needs to be
obtained from the classpath, or relative to a ServletContext. While it is possible to register new
handlers for specialized URL prefixes (similar to existing handlers for prefixes such as http:),
this is generally quite complicated, and the URL interface still lacks some desirable
functionality, such as a method to check for the existence of the resource being pointed to.
2 The Resource interface
Spring's Resource interface is meant to be a more capable interface for abstracting access to low-
level resources.
public interface Resource extends InputStreamSource {

boolean exists();

boolean isOpen();

URL getURL() throws IOException;

File getFile() throws IOException;

Resource createRelative(String relativePath) throws IOException;

String getFilename();

String getDescription();
}
public interface InputStreamSource {

InputStream getInputStream() throws IOException;


}
Some of the most important methods from the Resource interface are:
 getInputStream(): locates and opens the resource, returning an InputStream for reading
from the resource. It is expected that each invocation returns a fresh InputStream. It is the
responsibility of the caller to close the stream.
 exists(): returns a boolean indicating whether this resource actually exists in physical
form.
 isOpen(): returns a boolean indicating whether this resource represents a handle with an
open stream. If true, the InputStream cannot be read multiple times, and must be read
once only and then closed to avoid resource leaks. Will be false for all usual resource
implementations, with the exception of InputStreamResource.
 getDescription(): returns a description for this resource, to be used for error output when
working with the resource. This is often the fully qualified file name or the actual URL of
the resource.
Other methods allow you to obtain an actual URL or File object representing the resource (if the
underlying implementation is compatible, and supports that functionality).
The Resource abstraction is used extensively in Spring itself, as an argument type in many
method signatures when a resource is needed. Other methods in some Spring APIs (such as the
constructors to various ApplicationContext implementations), take a String which in unadorned
or simple form is used to create a Resource appropriate to that context implementation, or via
special prefixes on the String path, allow the caller to specify that a specific Resource
implementation must be created and used.
While the Resource interface is used a lot with Spring and by Spring, it's actually very useful to
use as a general utility class by itself in your own code, for access to resources, even when your
code doesn't know or care about any other parts of Spring. While this couples your code to
Spring, it really only couples it to this small set of utility classes, which are serving as a more
capable replacement for URL, and can be considered equivalent to any other library you would
use for this purpose.
It is important to note that the Resource abstraction does not replace functionality: it wraps it
where possible. For example, a UrlResource wraps a URL, and uses the wrapped URL to do its
work.
3 Built-in Resource implementations
There are a number of Resource implementations that come supplied straight out of the box in
Spring:
UrlResource
The UrlResource wraps a java.net.URL, and may be used to access any object that is normally
accessible via a URL, such as files, an HTTP target, an FTP target, etc. All URLs have a
standardized String representation, such that appropriate standardized prefixes are used to
indicate one URL type from another. This includes file: for accessing filesystem paths, http: for
accessing resources via the HTTP protocol, ftp: for accessing resources via FTP, etc.
A UrlResource is created by Java code explicitly using the UrlResource constructor, but will
often be created implicitly when you call an API method which takes a String argument which is
meant to represent a path. For the latter case, a JavaBeans PropertyEditor will ultimately decide
which type of Resource to create. If the path string contains a few well-known (to it, that is)
prefixes such as classpath:, it will create an appropriate specialized Resource for that prefix.
However, if it doesn't recognize the prefix, it will assume the this is just a standard URL string,
and will create a UrlResource.
ClassPathResource
This class represents a resource which should be obtained from the classpath. This uses either the
thread context class loader, a given class loader, or a given class for loading resources.
This Resource implementation supports resolution as java.io.File if the class path resource
resides in the file system, but not for classpath resources which reside in a jar and have not been
expanded (by the servlet engine, or whatever the environment is) to the filesystem. To address
this the various Resource implementations always support resolution as a java.net.URL.
A ClassPathResource is created by Java code explicitly using the ClassPathResource constructor,
but will often be created implicitly when you call an API method which takes a String argument
which is meant to represent a path. For the latter case, a JavaBeans PropertyEditor will recognize
the special prefix classpath:on the string path, and create a ClassPathResource in that case.
FileSystemResource
This is a Resource implementation for java.io.File handles. It obviously supports resolution as a
File, and as a URL.
ServletContextResource
This is a Resource implementation for ServletContext resources, interpreting relative paths
within the relevant web application's root directory.
This always supports stream access and URL access, but only allows java.io.File access when
the web application archive is expanded and the resource is physically on the filesystem.
Whether or not it's expanded and on the filesystem like this, or accessed directly from the JAR or
somewhere else like a DB (it's conceivable) is actually dependent on the Servlet container.
InputStreamResource
A Resource implementation for a given InputStream. This should only be used if no specific
Resource implementation is applicable. In particular, prefer ByteArrayResource or any of the
file-based Resource implementations where possible.
In contrast to other Resource implementations, this is a descriptor for an already opened resource
- therefore returning true from isOpen(). Do not use it if you need to keep the resource descriptor
somewhere, or if you need to read a stream multiple times.
ByteArrayResource
This is a Resource implementation for a given byte array. It creates a ByteArrayInputStream for
the given byte array.
It's useful for loading content from any given byte array, without having to resort to a single-use
InputStreamResource.
The ResourceLoader
The ResourceLoader interface is meant to be implemented by objects that can return (i.e. load)
Resource instances.
public interface ResourceLoader {
Resource getResource(String location);
}
All application contexts implement the ResourceLoader interface, and therefore all application
contexts may be used to obtain Resource instances.
When you call getResource() on a specific application context, and the location path specified
doesn't have a specific prefix, you will get back a Resource type that is appropriate to that
particular application context. For example, assume the following snippet of code was executed
against a ClassPathXmlApplicationContext instance:
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");
What would be returned would be a ClassPathResource; if the same method was executed
against a FileSystemXmlApplicationContext instance, you'd get back a FileSystemResource. For
a WebApplicationContext, you'd get back a ServletContextResource, and so on.
As such, you can load resources in a fashion appropriate to the particular application context.
On the other hand, you may also force ClassPathResource to be used, regardless of the
application context type, by specifying the special classpath: prefix:
Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");
Similarly, one can force a UrlResource to be used by specifying any of the standard
java.net.URL prefixes:
Resource template = ctx.getResource("file:/some/resource/path/myTemplate.txt");
Resource template = ctx.getResource("http://myhost.com/resource/path/myTemplate.txt");
The following table summarizes the strategy for converting Strings to Resources:
Resource strings
Prefix Example Explanation
classpath: classpath:com/myapp/config.xml Loaded from the classpath.
Prefix Example Explanation
file: file:/data/config.xml Loaded as a URL, from the filesystem. [1]
http: http://myserver/logo.png Loaded as a URL.
(none) /data/config.xml Depends on the underlying ApplicationContext.
[1]
But see also Section 4.7.3, “FileSystemResource caveats”.

The ResourceLoaderAware interface


The ResourceLoaderAware interface is a special marker interface, identifying objects that expect
to be provided with a ResourceLoader reference.
public interface ResourceLoaderAware {

void setResourceLoader(ResourceLoader resourceLoader);


}
When a class implements ResourceLoaderAware and is deployed into an application context (as
a Spring-managed bean), it is recognized as ResourceLoaderAware by the application context.
The application context will then invoke the setResourceLoader(ResourceLoader), supplying
itself as the argument (remember, all application contexts in Spring implement the
ResourceLoader interface).
Resources as dependencies
If the bean itself is going to determine and supply the resource path through some sort of
dynamic process, it probably makes sense for the bean to use the ResourceLoader interface to
load resources. Consider as an example the loading of a template of some sort, where the specific
resource that is needed depends on the role of the user. If the resources are static, it makes sense
to eliminate the use of the ResourceLoader interface completely, and just have the bean expose
the Resource properties it needs, and expect that they will be injected into it.
What makes it trivial to then inject these properties, is that all application contexts register and
use a special JavaBeans PropertyEditor which can convert String paths to Resource objects. So if
myBean has a template property of type Resource, it can be configured with a simple string for
that resource, as follows:
<bean id="myBean" class="...">
<property name="template" value="some/resource/path/myTemplate.txt"/>
</bean>
Note that the resource path has no prefix, so because the application context itself is going to be
used as the ResourceLoader, the resource itself will be loaded via a ClassPathResource,
FileSystemResource, or ServletContextResource (as appropriate) depending on the exact type of
the context.
If there is a need to force a specific Resource type to be used, then a prefix may be used. The
following two examples show how to force a ClassPathResource and a UrlResource (the latter
being used to access a filesystem file).
<property name="template" value="classpath:some/resource/path/myTemplate.txt">
<property name="template" value="file:/some/resource/path/myTemplate.txt"/>
Application contexts and Resource paths
Constructing application contexts
An application context constructor (for a specific application context type) generally takes a
string or array of strings as the location path(s) of the resource(s) such as XML files that make up
the definition of the context.
When such a location path doesn't have a prefix, the specific Resource type built from that path
and used to load the bean definitions, depends on and is appropriate to the specific application
context. For example, if you create a ClassPathXmlApplicationContext as follows:
ApplicationContext ctx = new ClassPathXmlApplicationContext("conf/appContext.xml");
The bean definitions will be loaded from the classpath, as a ClassPathResource will be used. But
if you create a FileSystemXmlApplicationContext as follows:
ApplicationContext ctx =
new FileSystemXmlApplicationContext("conf/appContext.xml");
The bean definition will be loaded from a filesystem location, in this case relative to the current
working directory.
Note that the use of the special classpath prefix or a standard URL prefix on the location path
will override the default type of Resource created to load the definition. So this
FileSystemXmlApplicationContext...
ApplicationContext ctx =
new FileSystemXmlApplicationContext("classpath:conf/appContext.xml");
... will actually load its bean definitions from the classpath. However, it is still a
FileSystemXmlApplicationContext. If it is subsequently used as a ResourceLoader, any
unprefixed paths will still be treated as filesystem paths.
Constructing ClassPathXmlApplicationContext instances - shortcuts
The ClassPathXmlApplicationContext exposes a number of constructors to enable convenient
instantiation. The basic idea is that one supplies merely a string array containing just the
filenames of the XML files themselves (without the leading path information), and one also
supplies a Class; the ClassPathXmlApplicationContext will derive the path information from the
supplied class.
An example will hopefully make this clear. Consider a directory layout that looks like this:
com/
foo/
services.xml
daos.xml
MessengerService.class
A ClassPathXmlApplicationContext instance composed of the beans defined in the 'services.xml'
and 'daos.xml' could be instantiated like so...
ApplicationContext ctx = new ClassPathXmlApplicationContext(
new String[] {"services.xml", "daos.xml"}, MessengerService.class);
Please do consult the Javadocs for the ClassPathXmlApplicationContext class for details of the
various constructors.
Mapping and Injecting Collections in Spring

Home/Spring Framework/Mapping and Injecting Collections in Spring


Spring Framework supports the injection of the Java Collection types List, Set, Map and
Properties. You can use XML as well as annotations based configurations. We will learn
Constructor, Setter, and Field injections for the collections using annotations based
configurations in this article. The complete code example is available in the GitHub code
repository.
I recommend understanding the basics of Dependency Injection in Spring if you are new to
Spring.
Collections injection using @Autowired
All we need is annotate the Collections like List, Set, Map with @Autowired annotation.
Alternatively, you can use @Inject annotation as well. We will explored the injections through
Constructor, Setters, and Field.
1. Constructor Injection for Collections (List, Set, Map)
2. Setter Injection for Collections (List, Set, Map)
3. Field Injection of Collections using @Autowired
1. Constructor Injection for Collections (List, Set, Map)
The Java collections Constructor Injection is done using the @Autowired annotation. Point to
note is, the Spring IoC should be able to find the beans with the respective types to inject. The
respective collection types are configured in CollectionsConfig.java.
 ConstructorInjection.java
 CollectionsConfig.java
 TestCI.java
1. @Component
2. public class ConstructorInjection {
3.
4. private List<String> names;
5. private Set<Long> phones;
6. private Map<Long, String> phoneNameMap;
7.
8. @Autowired
9. public ConstructorInjection(List<String> names, Set<Long> phones,
10. Map<Long, String> phoneNameMap) {
11. this.names = names;
12. this.phones = phones;
13. this.phoneNameMap = phoneNameMap;
14. }
15. //Getter, Setter, toString() omitted for bravity
16. }
Output:
ConstructorInjection[names=[Salman Khan, Hrithik Roshan], phones=[1212121212,
2222222222], phoneNameMap={888888888888=Ram, 777777777777=Bhim}]
Understand the bean configurations in CollectionsConfig.java, the method namesList() returns
List, numbersBean() returns Set and the phoneNameMapBean() returns the Map. These are then
@Autowired in ConstructorInjection.java.
2. Setter Injection for Collections (List, Set, Map)
All you have to do is place the @Autowired annotations on setters and make sure the respective
bean types are configured. In this case, we will use the same configurations from the previous
example CollectionsConfig.java.
1. @Component
2. public class SetterInjection {
3.
4. private List<String> names;
5. private Set<Long> phones;
6. private Map<Long, String> phoneNameMap;
7.
8. @Autowired
9. public void setNames(List<String> names) {
10. this.names = names;
11. }
12.
13. @Autowired
14. public void setPhones(Set<Long> phones) {
15. this.phones = phones;
16. }
17.
18. @Autowired
19. public void setPhoneNameMap(Map<Long, String> phoneNameMap) {
20. this.phoneNameMap = phoneNameMap;
21. }
22.
23. //toString() omitted for bravity.
24. }
3. Field Injection for Collections using @Autowired
To make the Spring IoC do field injection, place @Autowired annotations on the fields as shown
below. And obviously, you need to configure the beans to be injected in these collections fields
like CollectionsConfig.java from the first example.
It is not recommended to use the field-based injection as it has a performance impact. Use
either the constructor based injection or Setter based injection.
1. @Component
2. public class FieldInjection {
3.
4. @Autowired //Avoid using property injection
5. private List<String> names;
6.
7. @Autowired //Avoid using property injection
8. private Set<Long> phones;
9.
10. @Autowired //Avoid using property injection
11. private Map<Long, String> phoneNameMap;
12.
13. }
AOP with Spring Framework
One of the key components of Spring Framework is the Aspect oriented programming
(AOP) framework. Aspect-Oriented Programming entails breaking down program logic into
distinct parts called so-called concerns. The functions that span multiple points of an application
are called cross-cutting concerns and these cross-cutting concerns are conceptually separate
from the application's business logic. There are various common good examples of aspects like
logging, auditing, declarative transactions, security, caching, etc.
The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the
aspect. Dependency Injection helps you decouple your application objects from each other and
AOP helps you decouple cross-cutting concerns from the objects that they affect. AOP is like
triggers in programming languages such as Perl, .NET, Java, and others.
Spring AOP module provides interceptors to intercept an application. For example, when a
method is executed, you can add extra functionality before or after the method execution.
AOP Terminologies
Before we start working with AOP, let us become familiar with the AOP concepts and
terminology. These terms are not specific to Spring, rather they are related to AOP.
Sr.No Terms & Description
Aspect
This is a module which has a set of APIs providing cross-cutting requirements. For
1
example, a logging module would be called AOP aspect for logging. An application can
have any number of aspects depending on the requirement.
Join point
This represents a point in your application where you can plug-in the AOP aspect. You can
2
also say, it is the actual place in the application where an action will be taken using Spring
AOP framework.
3 Advice
This is the actual action to be taken either before or after the method execution. This is an
actual piece of code that is invoked during the program execution by Spring AOP
framework.
Pointcut
4 This is a set of one or more join points where an advice should be executed. You can
specify pointcuts using expressions or patterns as we will see in our AOP examples.
Introduction
5
An introduction allows you to add new methods or attributes to the existing classes.
Target object
6 The object being advised by one or more aspects. This object will always be a proxied
object, also referred to as the advised object.
Weaving
7 Weaving is the process of linking aspects with other application types or objects to create
an advised object. This can be done at compile time, load time, or at runtime.
Types of Advice
Spring aspects can work with five kinds of advice mentioned as follows −
Sr.No Advice & Description
before
1
Run advice before the a method execution.
after
2
Run advice after the method execution, regardless of its outcome.
after-returning
3
Run advice after the a method execution only if method completes successfully.
after-throwing
4
Run advice after the a method execution only if method exits by throwing an exception.
around
5
Run advice before and after the advised method is invoked.
Custom Aspects Implementation
Spring supports the @AspectJ annotation style approach and the schema-based approach to
implement custom aspects. These two approaches have been explained in detail in the following
sections.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy