5 Unit5 Part1
5 Unit5 Part1
Java(BCS-403)
Unit-5
Spring Framework
Table of Content
• Spring core basics ,Architecture
• Inversion of control
• Spring dependency injection concepts
• Aspect oriented programming (AOP)
• Bean Scopes- Singleton
• Prototype, Request, Session
• Application and Web Socket
• Auto-wiring
• Annotations
• Lifecycle call backs
• Beans configuration styles
Introduction to Spring Framework
❑Developing software applications is hard enough even with good tools and
technologies.
❑Implementing applications using platforms which promise everything but
turn out to be heavy-weight, hard to control and not very efficient during
the development cycle makes it even harder.
❑Spring provides a light-weight solution for building enterprise-ready
applications, while still supporting the possibility of using declarative
transaction management, remote access to your logic using RMI or web
services, and various options for persisting your data to a database.
❑It provides a full-featured MVC framework, and transparent ways of
integrating AOP into your software.
❑Advantages of Spring framework is its layered architecture, which allows
you to be selective about which of its components you use while also
providing a cohesive framework for J2EE application development.
Introduction to Spring Framework
▪ It is an application framework and inversion of control (IoC) container
for the Java platform.
▪ Its core features can be used by any Java application, but there are
extensions for building web applications on top of the Java EE
(Enterprise Edition) platform.
▪ It does not impose any specific programming model
▪ Spring has become popular in the Java community as an addition to
the Enterprise JavaBeans (EJB) model.
▪ It is free and open source software
Spring Framework Features(1)
• Features are well-organized in six modules shown in the diagram
below.
Object Relational
Data Access Object Mapping (ORM)
(DAO)
Model-View-Controller
(MVC)
Aspect Oriented
Programming (AOP)
Inversion of Control
(IoC)
Spring Framework Features
Features are well-organized in six modules shown in the diagram below.
• Core package is fundamental part and provides IoC and Dependency
Injection features. Here, BeanFactory provides a implementation of the
factory pattern which removes the need for programmatic singletons and
allows you to decouple the configuration and specification of
dependencies
• Context package build on the solid base provided by the Core package: it
provides a way to access objects in a framework-style manner in a
fashion somewhat reminiscent of a JNDI-registry. It inherits its features
from the beans package and adds support for internationalization.
Spring Framework Features
▪ DAO package provides a JDBC-abstraction layer that removes need to do
JDBC coding and parsing of database-vendor specific error codes. It also
provides a way to do programmatic as well as declarative transaction
management, not only for classes implementing special interfaces, but
for all your POJOs (plain old Java objects).
▪ ORM package provides integration layers for popular object-relational
mapping APIs, including JPA, JDO, Hibernate, and iBatis. Using the ORM
package you can use all those O/R-mappers in combination with all the
other features Spring offers, such as the simple declarative transaction
management feature mentioned previously.
Spring Framework Features
▪ AOP package provides an AOP Alliance-compliant aspect-oriented
programming implementation that allows method-interceptors and
pointcuts to cleanly decouple code implementing functionality that
should logically speaking be separated. Using source-level metadata
functionality you can also incorporate all kinds of behavioral information
into your code, in a manner similar to that of .NET attributes.
▪ Spring's Web package provides web-oriented integration features, such
as multipart file-upload functionality, initialization of the IoC container
using servlet listeners and a web-oriented application context. When
using Spring together with WebWork or Struts, this is package to
integrate with.
▪ Spring's MVC package provides a Model-View-Controller (MVC)
implementation for web-applications. It provides a clean separation
between domain model code and web forms, and allows you to use all
the other features of the Spring Framework.
Usage Scenario
With the building blocks,
use Spring in all sorts of
scenarios, from applets
up to fully-fledged
enterprise applications
using Spring's transaction
management
functionality and web
framework integration.
Java Example
using
constructor
Injection
Setter injection
• Accept dependencies through a setter method, clients can allow injectors to manipulate their
dependencies at any time. This offers flexibility, but makes it difficult to ensure that all
dependencies are injected and valid before the client is used.
Java Example
using setter
Injection
Aspect Oriented Programming
• It compliments OOPs in sense that it also provides modularity. But key
unit of modularity is aspect than class.
• AOP breaks 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 whole application
and should be centralized in one location in code as possible, such as
transaction management, authentication, logging, security etc.
Why use AOP?
• The service/domain classes get advised by aspects without adding any Spring AOP
related classes or interfaces into service/domain classes.
• Allows developer to concentrate on the business code, instead cross cutting
concerns.
• Easy to maintain and make changes to the aspects
• Changes need to be made in one place.
AOP concept and terminology
Aspect- A modularization of a concern that cuts across multiple classes.
Transaction management is a good example of a crosscutting concern in
enterprise Java applications. In Spring AOP, aspects are implemented by
regular classes annotated with the @aspect annotation.
Join point: A point during the execution of a program, such as the
execution of a method or the handling of an exception. In Spring AOP, a
join point always represents a method execution.
Advice: Action taken by an aspect at a particular join point. Different
types of advice include "around", "before", and "after" advice.Many AOP
frameworks, including Spring, model an advice as an interceptor and
maintain a chain of interceptors around the join point.
AOP concept and terminology
• Pointcut- A predicate that matches join points. Advice is associated
with a pointcut expression and runs at any join point matched by the
pointcut (ex., execution of a method with a certain name). The
concept of join points as matched by pointcut expressions is central
to AOP, and Spring uses the AspectJ pointcut expression language by
default.
• Introduction- Declaring additional methods or fields on behalf of a
type. Spring AOP lets you introduce new interfaces to any advised
object.
• Target object-An object being advised by one or more aspects. Also
referred to as the "advised object". Since Spring AOP is implemented
by using runtime proxies, this object is always a proxied object.
AOP concept and terminology
AOP proxy-
▪ An object created, in order to implement the aspect contracts (advice
method executions and so on).
▪ AOP proxy is a JDK dynamic proxy or a CGLIB proxy.
Weaving-
▪ linking aspects with other application types or objects to create an
advised object.
▪ This can be done at compile time (using the AspectJ compiler, for
example), load time, or at runtime. Spring AOP, like other pure Java
AOP frameworks, performs weaving at runtime.
AOP: Type of Advice
▪ Before advice- Advice that runs before a join point but that does not have the
ability to prevent execution flow proceeding to the join point (unless it throws
an exception).
▪ After returning advice-Advice to be run after a join point completes normally
(for example, if a method returns without throwing an exception).
▪ After throwing advice- Advice to be run if a method exits by throwing an
exception.
▪ After (finally) advice-Advice to be run regardless of the means by which a join
point exists.
▪ Around advice: Advice that surrounds a join point such as a method invocation.
Around advice can perform custom behavior before and after the method
invocation. It is also responsible for choosing whether to proceed to the join
point or to shortcut the advised method execution by returning its own return
value or throwing an exception.
Dependency Injection(DI) in Spring
▪ In Spring Objects are loosely coupled i.e., each class is independent of each other so
that everything can be tested individually. But when using those classes, a class may
be dependent on other classes which need to be instantiated first.
▪ Example- class A is dependent on class B. So, when creating bean(like class) for class
A, it instantiates class B prior to that of class A and injects that in class A using setter
or constructor DI methods. I.e., spring does injects this dependency at run-time. This
is DI.
Spring IOC Container
• It provides a mechanism to configure applications and integrates with almost all
Java environments, from small-scale applications to large enterprise applications.
• Programmer does not directly create an object, but describes how it should be
created, by defining it in the Spring configuration file.
▪ It is responsible for instantiating, configuring, and assembling the Spring beans.
▪ container gets its instructions on what objects to instantiate, configure, and
assemble by reading configuration metadata.
-
Types of Spring Containers
Spring framework provides two distinct types of containers.
▪ BeanFactory container
▪ ApplicationContext container
Open App.java
and run this
file.
• Step2: Open pom.xml and add the spring dependency in
<dependencies> </ dependencies> and save the changes
• <dependency>
• <groupId>org.springframework</groupId>
• <artifactId>spring-context</artifactId>
• <version>6.0.12</version>
• </dependency>
• <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
• <dependency>
• <groupId>org.springframework</groupId>
• <artifactId>spring-core</artifactId>
• <version>6.0.12</version>
• </dependency>
Step 3: Create a package in src/main/java named as
“com.spring.corespring” and create bean class(java class ) and named it
as “Student”.
• Write the definition of the bean here:
Step4: Create a folder “resources” in src/main (available just after JRE
System Library), inside the resources folder create an xml file named as
“xmlconfig”.
• And write the beans setting data here:
• <beans xmlns="http://www.springframework.org/schema/beans"
• xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
• xmlns:p="http://www.springframework.org/schema/p"
• xsi:schemaLocation="http://www.springframework.org/schema/beans
• http://www.springframework.org/schema/beans/spring-beans.xsd
• http://www.springframework.org/schema/context
• http://www.springframework.org/schema/context/spring-context.xsd">
• Step5: Open App.java file and write code to connect with xml
configuration,
Java Based Configuration
• To implement java Based configuration, we will use java based
configuration instead of xml based.
• For this we need to use two different annotation, Configuration and
Bean.
• Step1: in previous project, need to add one more class that will be our
configuration class, take name a AppConfig.java in main package[]
• AppConfig.java
In main class(App.java)[If any loading issue of AppConfig then change
jdk and compatible spring version in pom.xml/ also change jre in project ]
• We can instantiate an AnnotationConfigApplicationContext by using a
no-arg constructor and then
• configure it by using the register() method.
AppConfig class
Bean Lifecycle
• Similarly, bean life cycle refers to when & how the bean is instantiated, what
action it performs until it lives, and when & how it is destroyed.
• Bean life cycle is managed by the spring container. When we run the program
then, first of all, the spring container gets started.
• Container creates the instance of a bean as per the request, and then
dependencies are injected.
• And finally, the bean is destroyed when the spring container is closed.
Customizing nature of a bean
▪ Lifecycle callbacks
-Initialization callbacks
-Destruction callbacks
-Default initialization & destroy methods
-Combining lifecycle mechanisms
-Shutting down the Spring IoC container gracefully in non-web applications
▪ Knowing who you are
-BeanFactoryAware
-BeanNameAware
LifeCycle CallBack
• Provides several callback interfaces to change the behaviour of your bean in
the container, they include InitializingBean and DisposableBean.
• lifecycle callbacks are mechanisms provided to manage the lifecycle of Spring
beans.
• These callbacks allow you to perform certain actions during different phases
of a bean's lifecycle, such as initialization and destruction.
-@PostConstruct
-@PreDestroy Annotation
▪ Using these annotations means that your beans are not bound to Spring-specific
interfaces.
@PostConstruct
• annotation on a method that should be called after dependency
injection is complete to perform initialization tasks.
• import javax.annotation.PostConstruct;
• public class MyBean {
• @PostConstruct
• public void init()
• { // Custom initialization logic here
• }
• }
• @PreDestroy Annotation:
• You can use the @PreDestroy annotation on a method that should be
called just before a bean is removed from the container to perform
cleanup tasks.
• import javax.annotation.PreDestroy;