Spring

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Spring is a lightweight(it doesn't reinvent the wheel and builds on top of existing

technologies and standards) framework(body or platform of pre-written codes used


by Java developers to develop Java applications or web applications). 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.

Inversion of Control
1. 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.
2. The IoC container is responsible to instantiate the application class, configure the
object and assemble the dependencies between the objects. The IoC container
gets information from the XML file and works accordingly.
3. Two types of IoC containers. They are:
i. org.springframework.beans.factory.BeanFactory interface
ii. org.springframework.context.ApplicationContext interface
Eg: inversion-of-control-with-example

Dependency Injection
Dependency injection is a design pattern we can use to implement IoC, where the
control being inverted is setting an object's dependencies( “injecting” objects into
other objects).It 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.Two ways to inject dependency: constructor and
setter method
Eg: spring-dependency-injection-with-example

Advantages of Spring
1. Predefined Template- Spring framework provides templates, so there is no need
to write too much code.Eg: Like JdbcTemplate, you don't need to write the code
for exception handling, creating connection, creating statement, committing
transaction, closing connection etc. You need to write the code of executing
query only.
2. Lightweight- Spring framework is lightweight because of its POJO
implementation. The Spring Framework doesn't force the programmer to inherit
any class or implement any interface.
3. Loose Coupling- The Spring applications are loosely coupled because of
dependency injection.

Spring Modules and Framework

1. Simple Spring Application


Create a simple POJO(Plain Old Java Object) class, for example Student class
with one instance variable “name” with appropriate getter and setter method with
displayInfo method to print “name” variable.
2. Create an XML
file
“applicationContext.x
ml”
The bean element is
used to define the
bean(the objects that
form the backbone of
your application that is
instantiated, assembled,
and otherwise managed
by a Spring IoC
container. Otherwise, a
bean is simply one of many objects in your application). for the given class.
The property sub-element of bean specifies the property of the Student class named
name. The value specified in the property element will be set in the Student class
object by the IOC container.
3. Create a Main
class to get the object
of Student class from
IOC
The Resource(to access
external
resources) object
represents the
information of
applicationContext.xml
file. The Resource is the
interface and
the ClassPathResource
is the implementation
class of the Resource interface. The BeanFactory is responsible to holds bean
definitions and instantiates/return them whenever asked for by the client application –
which means: It takes care of the lifecycle of a bean. The XmlBeanFactory is the
implementation class of the BeanFactory. There are many methods in the
BeanFactory interface. One method is getBean(), which returns the object of the
associated class.

Using ApplicationContext interface


ApplicationContext context = new ClassPathXmlApplicationContext("applicationCo
ntext.xml");
Difference between BeanFactory and the ApplicationContext

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.
Dependency Injection using

Constructor
1. The ref attribute is
used to define the
reference of another
object, such way we are
passing the dependent
object as an constructor
argument.

2. To insert List we use


<List> element with
<value> as its child
element under
<constructor-args>
element. Similarly to
insert Map we use <Map>
element with <entry
key=” ” value=” ”> as its
child element under
<constructor-args>
element.

Setter Method

We use <property name=” “ value=” “ ref=” “> element


To insert List we use <List> element with <value> as its child element under
<property name=” “> element. Similarly to insert Map we use <Map> element with
<entry key=” ” value=” ”> as its child element under <property name=” “> element.

Difference between Constructor injection and Setter method

Autowiring
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.
Mode Description
byName
The byName mode injects the object dependency according to name of the bean. In suc
and bean name must be same. It internally calls setter method.
byType The byType mode injects the object dependency according to type. So
property name and bean name can be different. It internally calls setter
method.If you have multiple bean of one type, it will not work and
throw exception.
constructor The constructor mode injects the dependency by calling the constructor
of the class. It calls the constructor having large number of parameters.
no It is the default autowiring mode. It means no autowiring bydefault.
For better understanding
Aspect Oriented Programming (AOP)

Compliments OOPs in the sense that it also provides modularity( let the development
of software be divided into several components that can be implemented
simultaneously by the team of developers.). But the key unit of modularity is aspect
than class.

Let say of an example there are 5 methods that starts from m, 2 methods that starts
from n and 3 methods that starts from p.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 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.

AOP concepts

Join Point- 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:

i. Before Advice(@Before): It executes before a join point.


ii. After Returning Advice(@After):It executes after a joint point completes
normally and before returning.
iii. After Throwing Advice(@AfterThrowing): It executes if method exits by
throwing an exception.
iv. After (finally) Advice:It executes after a join point regardless of join point exit
whether normally or exceptional return.
v. Around Advice(@Around): It executes before and after a join point.

Pointcut(@Pointcut())- It is an expression language of AOP that are matched with


join points to determine whether advice needs to be executed or not.

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

Understanding Pointcut expression

@Pointcut("execution(public * *(..))")- Applied to all public methods


@Pointcut("execution(public Operation.*(..))")-Applied to all public method of
operation class
@Pointcut("execution(* Operation.*(..))")-Applied to all method of operation
class.
@Pointcut("execution(public Employee.set*(..))")-Applied to public setter
method of Employee class
@Pointcut("execution(int Operation.*(..))")-Applied to int return type method
of operation class

Spring AspectJ AOP Implementations


Using Annotations
Using XML Configuration

Spring JDBC Template


Is a powerful mechanism to connect to the database and execute SQL queries. It
internally uses JDBC api, but eliminates a lot of problems of JDBC API.
Spring framework provides following approaches for JDBC database access:
i. JdbcTemplate
ii. NamedParameterJdbcTemplate
iii. SimpleJdbcTemplate
iv. SimpleJdbcInsert and SimpleJdbcCall

Spring with ORM Framework

Spring provides API to easily integrate Spring with Object Relational Mapping
(ORM)(is a technique used in creating a "bridge" between object-oriented programs
and relational databases or you can see the ORM as the layer that connects object
oriented programming (OOP) to relational databases.) frameworks such as Hibernate,
JPA(Java Persistence API), JDO(Java Data Objects), Oracle Toplink and iBATIS.
Java classes whose objects or instances will be stored in database tables are called
persistent classes in hibernate.
Spring with Hibernate
* Spring with JPA(Java Persistent API)

Product DAO impl implements Product DAO interface which uses hibernate
template which requires sessionfactory bean for which LocalSessionFactory
bean is a implementation

LocalSessionFactory bean requires DataSource,hbernate properties and list of


annotated classes(to tell LocalSessionFactory bean which classes are mapped to
database tables)

Hibernate properties are provided in key:value pair


Hibernate.dialect=org.hibernate.dialect.MYSQLDialect (to generate sql queries)
Hibernate.show_sql=true (to display sql queries)
Spring MVC
From Spring 3.0 we can configure the application using Java class rather than a XML

file.Java configuration file should be marked with @configuration annotation to tell

the application that this class is the source of spring beans,in this class we can define

multiple methods that returns beans of the different class,these method are marked

with @bean annotation.

You might also like