0% found this document useful (0 votes)
25 views23 pages

UNIT4

The document discusses the Spring framework. Spring is a lightweight Java framework that provides inversion of control and dependency injection. It comprises several modules including core, beans, context, AOP, and web. The document also explains dependency injection in Spring and the difference between BeanFactory and ApplicationContext.

Uploaded by

Mudit Rajput
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views23 pages

UNIT4

The document discusses the Spring framework. Spring is a lightweight Java framework that provides inversion of control and dependency injection. It comprises several modules including core, beans, context, AOP, and web. The document also explains dependency injection in Spring and the difference between BeanFactory and ApplicationContext.

Uploaded by

Mudit Rajput
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

UNIT 4

Spring Framework
Spring is a lightweight framework developed by Rod Johnson in 2003. It can
be thought of as a framework of frameworks because it provides support to
various frameworks such as Struts,, Hibernate, Tapestry, EJB, JSF, etc. The
framework, in broader sense, can be defined as a structure where we find solution of
the various technical problems.

The Spring framework comprises several modules such as IOC, AOP, DAO,
Context, ORM, WEB MVC etc.

Spring Modules
The Spring framework comprises of many modules such as core, beans, context,
expression language, AOP, Aspects, Instrumentation, JDBC, ORM, OXM, JMS,
Transaction, Web, Servlet, Struts etc. These modules are grouped into Test,
Core Container, AOP, Aspects, Instrumentation, Data Access / Integration, Web
(MVC / Remoting) as displayed in the following diagram.
Test
This layer provides support of testing with JUnit and TestNG.

Spring Core Container


The Spring Core container contains core, beans, context and expression
language (EL) modules.

1. Core and Beans

These modules provide IOC and Dependency Injection features.

2. Context

This module supports internationalization (I18N), EJB, JMS, Basic


Remoting.

3. Expression Language(Spel)

It is an extension to the EL defined in JSP. It provides support to


setting and getting property values, method invocation, accessing
collections and indexers, named variables, logical and arithmetic
operators, retrieval of objects by name etc.

AOP, Aspects and Instrumentation


These modules support aspect oriented programming implementation
where you can use Advices, Pointcuts etc. to decouple the code.

The aspects module provides support to integration with AspectJ.

The instrumentation module provides support to class instrumentation and


classloader implementations.

Data Access / Integration


This group comprises of JDBC, ORM, OXM, JMS and Transaction modules.
These modules basically provide support to interact with the database.
Web
This group comprises of Web, Web-Servlet, Web-Struts and Web-Portlet.
These modules provide support to create web application.

IoC Container
The IoC container is responsible to instantiate, configure and assemble the
objects. The IoC container gets informations from the XML file and works
accordingly. The main tasks performed by IoC container are:

o to instantiate the application class


o to configure the object
o to assemble the dependencies between the objects

There are two types of IoC containers. They are:

1. BeanFactory
2. ApplicationContext

Difference between BeanFactory and ApplicationContext


ApplicationContext interfaces acts as the IoC container. The ApplicationContext
interface is built on top of the BeanFactory interface. It adds 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.

Using BeanFactory
The XmlBeanFactory is the implementation class for the BeanFactory interface. To
use the BeanFactory, we need to create the instance of XmlBeanFactory class as
given below:

1. Resource resource=new ClassPathResource("applicationContext.xml");


2. BeanFactory factory=new XmlBeanFactory(resource);
Using ApplicationContext

The ClassPathXmlApplicationContext class is the implementation class of


ApplicationContext interface. We need to instantiate the
ClassPathXmlApplicationContext class to use the ApplicationContext as given
below:

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

The constructor of ClassPathXmlApplicationContext class receives string, so we


can pass the name of the xml file to create the instance of ApplicationContext.

Dependency Injection in Spring


Dependency Injection (DI) is a design pattern that removes the dependency from
the programming code so that it can be easy to manage and test the application.
Dependency Injection makes our programming code loosely coupled. To
understand the DI better, Let's understand the Dependency Lookup (DL) first:

Dependency Lookup
The Dependency Lookup is an approach where we get the resource after
demand. There can be various ways to get the resource for example:

Aobj = new AImpl(); In such way, we get the resource(instance of A class)


directly by new keyword. Another way is factory method:

A obj = A.getA(); This way, we get the resource (instance of A class) by calling
the static factory method getA().

Problems of Dependency Lookup

There are mainly two problems of dependency lookup.


o Tight coupling The dependency lookup approach makes the code tightly
coupled. If resource is changed, we need to perform a lot of modification
in the code.
o Not easy for testing This approach creates a lot of problems while testing
the application especially in black box testing.

1. 20.5M

Dependency Injection
The Dependency Injection is a design pattern that removes the dependency of
the programs. In such case we provide the information from the external source
such as XML file. It makes our code loosely coupled and easier for testing. In such
case we write the code as:

class Employee
{
Address address;

Employee(Address address)
{
this.address=address;
}
public void setAddress(Address address)
{
this.address=address;
}

In such case, instance of Address class is provided by external source such as XML
file either by constructor or setter method.
Two ways to perform Dependency Injection in
Spring framework
Spring framework provides two ways to inject dependency

2. By Constructor
3. By Setter method

Dependency Injection by Constructor Example


We can inject the dependency by constructor. The <constructor-
arg> subelement of <bean> is used for constructor injection. Here we are going
to inject

1. primitive and String-based values


2. Dependent object (contained object)
3. Collection values etc.

Injecting primitive and string-based values


Let's see the simple example to inject primitive and string-based values. We have
created three files here:

1. Employee.java
2. applicationContext.xml
3. Test.java

Employee.java

public class Employee {


private int id;
private String name;

public Employee() {System.out.println("def cons");}


public Employee(int id) {this.id = id;}

public Employee(String name) { this.name = name;}

public Employee(int id, String name) {


this.id = id;
this.name = name;
}

void show(){
System.out.println(id+" "+name);
}

}
applicationContext.xml

We are providing the information into the bean by this file. The constructor-arg
element invokes the constructor. In such case, parameterized constructor of int
type will be invoked. The value attribute of constructor-arg element will assign
the specified value. The type attribute specifies that int parameter constructor will
be invoked.

<?xml version="1.0" encoding="UTF-8"?>


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

<bean id="e" class="com.javatpoint.Employee">


<constructor-arg value="10" type="int"></constructor-arg>
</bean>

</beans>

Test.java

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;

public class Test {


public static void main(String[] args) {

Resource r=new ClassPathResource("applicationContext.xml");


BeanFactory factory=new XmlBeanFactory(r);

Employee s=(Employee)factory.getBean("e");
s.show();

}
}

Injecting string-based values


If you don't specify the type attribute in the constructor-arg element, by default
string type constructor will be invoked.

<bean id="e" class="com.javatpoint.Employee">


<constructor-arg value="10"></constructor-arg>
</bean>
Design Pattern in Spring
“In software engineering, a software design pattern is a general, reusable
solution to a commonly occurring problem within a given context in software
design. It is not a finished design that can be transformed directly into
a source or machine code. Rather, it is a description or template for
how to solve a problem that can be used in many different situations.
Design patterns are formalized best practices that the programmer can use
to solve common problems when designing an application or system.”

Using a Design Pattern doesn’t depend on what language you are


using? Maybe Java or Kotlin language. I highly recommend using Kotlin
language for new your project. Some projects, have used Java language
when the project started. You should refactor them by small steps if you
wanna use Kotlin language.

1. Inversion of Control (IOC)

In my option, it’s a pattern. Some people have assumed it is a principle.


Have you read Martin Fowler Blog about IoC yet? Martin Fowler has called
it a principle also known as the Hollywood Principle — “Don’t call us, we’ll
call you”. There is a little confusion here. What is the difference between
IOC and DIP (Dependency Inversion Principle)? Here is my answer: When
we use IOC that will guarantee your code abide by DIP. IOC only is a
programming technique.
In the Spring project, we have IOC Container which helps us to manage
beans in our application: initialize, manage, destroy bean life cycle. In
my option, IOC is only about project structure and Dependency
Injection is about “How to works?”.

Singleton Pattern

In the spring framework, IOC manages a lot of beans. As a default, a bean


is created which has a singleton scope. Singleton means “A class of
which only a single instance can exit”. So, How to set a singleton in the
project? It’s very simple. The answer is very difficult to singleton setting
correctly. In Java, we have a Reflection API which can edit access modifier
of methods. Moreover, we have to pay attention to concurrency (Use
synchronized keyword). Besides, we still need to handle logic save/load
data from JSON data (Serialize/Deserialize object). Finally, Here is my
advice: If you can use static variables instead of singleton then you
should use static variables. It will guarantee your code which is only
one instance that exists in the whole application.

Factory Pattern

This pattern is used by spring to load beans using BeanFactory and


ApplicationContext. What is the difference between BeanFactory and
ApplicationContent?

In Short, the BeanFactory provides the configuration framework and basic


functionality, and the ApplicationContext adds more enterprise-specific
functionality. The ApplicationContext includes all the functionality of a
BeanFactory. So, you should use an ApplicationContext unless you have a
good reason.

Strategy Pattern

Basically, the Strategy Pattern is a behavioral software design pattern that


enables selecting an algorithm at runtime. Applying Strategy Pattern in your
code will guarantee your code abide by the Open/Closed Principle. This
principle is applied widely in everywhere. For example, you can imagine to
plugin architecture in IntelliJ IDEA/Visual Studio Code: make to easy for
adding/modifying a feature with an available plugin.

Spring AOP
Aspect Oriented Programming (AOP) compliments OOPs in the sense that it
also provides modularity. But the key unit of modularity is aspect than class.

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.

Why use AOP?

It provides the pluggable way to dynamically add the additional concern before,
after or around the actual logic. Suppose there are 10 methods in a class as given
below:

class A{
public void m1(){...}
public void m2(){...}
public void m3(){...}
public void m4(){...}
public void m5(){...}
public void n1(){...}
public void n2(){...}
public void p1(){...}
public void p2(){...}
public void p3(){...}
}

There are 5 methods that starts from m, 2 methods that starts from n and 3
methods that starts from p.

Understanding Scenario I have to maintain log and send notification after


calling methods that starts from m.

Problem without AOP We can call methods (that maintains log and sends
notification) from the methods starting with m. In such scenario, we need
to write the code in all the 5 methods.

But, if client says in future, I don't have to send notification, you need to
change all the methods. It leads to the maintenance problem.

Solution with AOP We don't have to call methods from the method. Now
we can define the additional concern like maintaining log, sending
notification etc. in the method of a class. Its entry is given in the xml file.

In future, if client says to remove the notifier functionality, we need to


change only in the xml file. So, maintenance is easy in AOP.

Where use AOP?

AOP is mostly used in following cases:

o to provide declarative enterprise services such as declarative transaction


management.
o It allows users to implement custom aspects.

AOP Concepts and Terminology


AOP concepts and terminologies are as follows:
Join point

Join point is any point in your program such as method execution, exception
handling, field access etc. Spring supports only method execution join point.

Advice

Advice represents an action taken by an aspect at a particular join point. There


are different types of advices:

o Before Advice: it executes before a join point.


o After Returning Advice: it executes after a joint point completes normally.
o After Throwing Advice: it executes if method exits by throwing an
exception.
o After (finally) Advice: it executes after a join point regardless of join point
exit whether normally or exceptional return.
o Around Advice: It executes before and after a join point.

Pointcut

It is an expression language of AOP that matches join points.

Introduction

It means introduction of additional method and fields for a type. It allows you to
introduce new interface to any advised object.

Target Object

It is the object i.e. being advised by one or more aspects. It is also known as
proxied object in spring because Spring AOP is implemented using runtime
proxies.
Aspect

It is a class that contains advices, joinpoints etc.

Interceptor

It is an aspect that contains only one advice.

AOP Proxy

It is used to implement aspect contracts, created by AOP framework. It will be a


JDK dynamic proxy or CGLIB proxy in spring framework.

Weaving

It is the process of linking aspect with other application types or objects to create
an advised object. Weaving can be done at compile time, load time or runtime.
Spring AOP performs weaving at runtime.

AOP Implementations
AOP implementations are provided by:

1. AspectJ
2. Spring AOP
3. JBoss AOP

Inversion of Control

Inversion of Control is a principle in software engineering which transfers


the control of objects or portions of a program to a container or framework.
We most often use it in the context of object-oriented programming.
In contrast with traditional programming, in which our custom code makes
calls to a library, IoC enables a framework to take control of the flow of
a program and make calls to our custom code. To enable this,
frameworks use abstractions with additional behavior built in. If we
want to add our own behavior, we need to extend the classes of the
framework or plugin our own classes.

The advantages of this architecture are:

 decoupling the execution of a task from its implementation


 making it easier to switch between different implementations
 greater modularity of a program
 greater ease in testing a program by isolating a component or
mocking its dependencies, and allowing components to communicate
through contracts

We can achieve Inversion of Control through various mechanisms such as:


Strategy design pattern, Service Locator pattern, Factory pattern, and
Dependency Injection (DI).

Spring – Beans

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 . 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

Spring – Beans Scope


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.

1 singleton
This scopes the bean definition to a single instance per Spring IoC container (default).

2 prototype
This scopes a single bean definition to have any number of object instances.

3 request
This scopes a bean definition to an HTTP request. Only valid in the context of a web-
aware Spring ApplicationContext.

4 session
This scopes a bean definition to an HTTP session. Only valid in the context of a web-
aware Spring ApplicationContext.

5 global-session
This scopes a bean definition to a global HTTP session. Only valid in the context

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.

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.

Autowiring in Spring
Autowiring feature of spring framework enables you to inject the object
dependency implicitly. It internally uses setter or constructor injection.

Autowiring can't be used to inject primitive and string values. It works with
reference only.

Advantage of Autowiring
It requires the less code because we don't need to write the code to inject the
dependency explicitly.

Disadvantage of Autowiring

No control of programmer.
Autowiring Modes

Following are the autowiring modes, which can be used to instruct the Spring
container to use autowiring for dependency injection. You use the autowire
attribute of the <bean/> element to specify autowire mode for a bean definition.

Mode & Description

1 no

This is default setting which means no autowiring and you should use explicit bean
reference for wiring. You have nothing to do special for this wiring. This is what you
already have seen in Dependency Injection chapter.

2 byName
Autowiring by property name. Spring container looks at the properties of the beans
on which autowire attribute is set to byName in the XML configuration file. It then
tries to match and wire its properties with the beans defined by the same names in
the configuration file.

3 byType
Autowiring by property datatype. Spring container looks at the properties of the
beans on which autowire attribute is set to byType in the XML configuration file. It
then tries to match and wire a property if its type matches with exactly one of the
beans name in configuration file. If more than one such beans exists, a fatal
exception is thrown.

4 constructor
Similar to byType, but type applies to constructor arguments. If there is not exactly
one bean of the constructor argument type in the container, a fatal error is raised.
5 autodetect
Spring first tries to wire using autowire by constructor, if it does not work, Spring
tries to autowire by byType.

Spring Annotation
Spring Framework started using annotations from the release 2.5. Due to
the way they are defined, annotations provide a lot of context in their
declaration.

Prior to annotations, the behavior of the Spring Framework was largely


controlled through XML configuration. Today, the use of annotations
provide us tremendous capabilities in how we configure the behaviors of
the Spring Framework.

Core Spring Framework Annotations


@Required

This annotation is applied on bean setter methods. Consider a scenario


where you need to enforce a required property. The @Required
annotation indicates that the affected bean must be populated at
configuration time with the required property. Otherwise an exception of
type BeanInitializationException is thrown.

@Autowired

This annotation is applied on fields, setter methods, and constructors.


The @Autowired annotation injects object dependency implicitly. When
you use
@Autowired on fields and pass the values for the fields using the
property name, Spring will automatically assign the fields with the passed
values.
@Qualifier

This annotation is used along with @Autowired annotation. When you


need more control of the dependency injection process, @Qualifier can be
used. @Qualifier can be specified on individual constructor arguments or
method parameters. This annotation is used to avoid confusion which
occurs when you create more than one bean of the same type and want to
wire only one of them with a property.

@Configuration

This annotation is used on classes which define beans. @Configuration is


an analog for XML configuration file – it is configuration using Java class.
Java class annotated with @Configuration is a configuration by itself and
will have methods to instantiate and configure the dependencies.

@ComponentScan

This annotation is used with @Configuration annotation to allow Spring to


know the packages to scan for annotated
components. @ComponentScan is also used to specify base packages
using basePackageClasses or basePackage attributes to scan. If specific
packages are not defined, scanning will occur from the package of the
class that declares this annotation.
@Bean

This annotation is used at the method level. @Bean annotation works


with @Configuration

to create Spring beans. As mentioned earlier, @Configuration will have


methods to instantiate and configure dependencies. Such methods will be
annotated with @Bean. The method annotated with this annotation works
as bean ID and it creates and returns the actual bean.

Spring bean life cycle


The Spring bean life cycle is easy to understand. When a bean is instantiated, it may be
required to perform some initialization to get it into a usable state. Similarly, when the
bean is no longer required and is removed from the container, some cleanup may be
required.

Though, there is lists of the activities that take place behind the scenes between the
time of bean Instantiation and its destruction, but this chapter will discuss only two
important bean life cycle callback methods which are required at the time of bean
initialization and its destruction.

Beans can be notified after creation and all properties are set, and before they are
destroyed and removed from the bean container. This involves specifying the callback
method to be invoked by the container. This is done in XML by specifying attributes init-
method=”myinit”, for the initialization callback, and destroy-method=”mydestroy”, for the
destroy callback. “myinit” and “cleanUp” are names of instance methods in the bean
class.
Initialization callbacks
Implementingthe org.springframework.beans.factory.InitializingBean interfa
ce allows a bean to perform initialization work after all necessary properties
on the bean are set by the container. The InitializingBean interface
specifies exactly one method:

void afterPropertiesSet() throws Exception

Destruction callbacks
Implementingthe org.springframework.beans.factory.DisposableBean interf
ace allows a bean to get a callback when the container containing it is
destroyed. The DisposableBean interface specifies one method:

void destroy() throws Exception

You might also like