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

5 Unit5 Part1

unit 5

Uploaded by

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

5 Unit5 Part1

unit 5

Uploaded by

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

Object Oriented Programming with

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.

Typical full-fledged Spring web application


Inversion of control Principle
▪ In software engineering, inversion of control (IoC) is a design principle
in which custom-written portions of a computer program receive
the flow of control from a generic framework.
▪ Any software architecture with this design "inverts" control as
compared to procedural programming.
▪ In procedural programming, a program's custom code calls reusable
libraries to take care of generic tasks, but with inversion of control, it is
the framework that calls the custom code.
▪ Inversion of control is sometimes referred to as the "Hollywood
Principle: Don't call us, we'll call you"
Types of Inversion of Control
▪ There are several basic design patterns which are used to implement IoC
in object-oriented programming.
-Using dependency injection pattern
-Using a contextualized lookup
-Using template method design pattern
Dependency Injection
▪ In software engineering, dependency injection is a programming technique in which
an object or function receives other objects or functions that it requires, as opposed to
creating them internally.
▪ It aims to separate the concerns of constructing objects and using them, leading
to loosely coupled programs.
▪ It ensures that an object/function that wants to use a given service should not have to
know how to construct those services. Instead, receiving 'client' (object or function) is
provided with its dependencies by external code (an 'injector'), which it is not aware
of.
▪ Dependency injection makes implicit dependencies explicit and helps solve the
following problems
-How can a class be independent from the creation of the objects it depends on?
-How can an application, and the objects it uses support different configurations?
Advantage of Dependency Injection
• It decreases coupling between classes and their dependencies.
• By removing a client's knowledge of how its dependencies are implemented, programs
become more reusable, testable and maintainable.
• Increased flexibility: a client may act on anything that supports the intrinsic interface
the client expects.
• It reduces boilerplate code since all dependency creation is handled by a singular
component.
• Allows concurrent development. Two developers can independently develop classes
that use each other, while only needing to know interface the classes will communicate
through. Plugins are often developed by third-parties that never even talk to
developers of the original product.
Types of Dependency Injection
1. Constructor injection- dependencies are provided through a client's
class constructor.
2. Setter injection- the client exposes a setter method which accepts
the dependency.
3. Interface injection- The dependency's interface provides an injector
method that will inject the dependency into any client passed to it.
Constructor injection
• common form of DI is, where a class requests its dependencies through its constructor.
This ensures the client is always in a valid state, since it cannot be instantiated without
its necessary dependencies.

Java Example without using


Dependency Injection

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 without using


Dependency Injection

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

❑ Note: The org.springframework.beans and org.springframework.context packages are the


basis for Spring Framework’s IoC container
Spring Beans
▪ objects that form backbone of application and managed by the Spring IoC container
are referred to as beans
▪ Or, POJO’s(plain old java object) are call ‘beans’ and those objects instantiated,
managed, Created by Spring IOC container.
▪ Beans are created with configuration metadata (XML file) that we supply to the
container
▪ Bean definition contains configuration metadata. With this information container
knows how to create bean, beans lifecycle, bean dependencies.
▪ After specifying objects of an application, instance of those objects will be reached by
getBean() method
What is BeanFactory
▪ BeanFactory is actual container which instantiates, configures, and
manages a number of beans. These beans typically collaborate with one
another, and thus have dependencies between themselves.
▪ Dependencies are reflected in configuration data used by the
BeanFactory (although some dependencies may not be visible as
configuration data, but rather be a function of programmatic interactions
between beans at runtime).
▪A BeanFactory is represented by the interface
org.springframework.beans.factory.BeanFactory
▪ The most commonly used simple BeanFactory implementation is
org.springframework.beans.factory.xml.XmlBeanFactory.
ApplicationContext
▪ BeanFactory is the root interface for accessing the Spring container. It
provides basic functionalities for managing beans.
▪ ApplicationContext is a sub-interface of the BeanFactory. Therefore, it
offers all the functionalities of BeanFactory.
▪ Furthermore, it provides more enterprise-specific functionalities. The
important features of ApplicationContext are resolving messages,
supporting internationalization, publishing events, and application-layer
specific contexts.
Configuration Metadata
Three ways we can supply Configuration Metadata to Spring IoC
container:
▪ XML –based configuration
▪ Annotation –based configuration
▪ Java –based configuration
XML based Configuration
▪ create an xml file and initialize bean property value in this xml file.
▪ To write the code for implementation, we need to create a project
using any IDE and do some integration part for spring and add some
relevant file for execution.
▪ For implementation we need following tools and API:
- JDK
-SPRING API
-MAVEN Build tool
-Eclipse IDE version
Annotation –based configuration
• This operates on metadata in the component class itself by using annotations on
the relevant class, method, or field declaration.
• Once the tag <context:annotation-config/> is configured you have the authority
to start annotating your code.
• It will indicate that the Spring should automatically wire the values into
properties methods and constructors.
Annotation List
▪ @Required: It is applicable to bean property setter methods.
▪ @Autowired: It is only applied to the bean property setter methods,
constructors, non-setter methods and properties.
▪ @Qualifier: This Spring Framework annotation along with the
@Autowired is used for removing the confusion by specifying the exact
bean to wire.
▪ JSR-250 Annotations: These Spring annotations are supported by Spring
Framework including @Resource, @PreDestroy and @PostConstruct
annotations. These annotations are not really required as you already
have the alternatives.
Java –based configuration
• It enables you to write most of your Spring configuration without XML but with the
help of few Java-based annotations.
• For Example- @Configuration & @Bean Annotations
• @Configuration indicates that the class can be used by the Spring IoC container as a
source of bean definitions.
• @Bean annotation tells Spring that a method annotated with @Bean will return an
object that should be registered as a bean in the Spring application context.
Steps to create Project (Maven Project)
Maven is a powerful project management tool that is based on POM (project object
model). It is used for project build, dependency, and documentation
Step1: Open your Eclipse
• File-> new project-> Maven Project→Select your project location(Browse)->Filter
• Search
• Group_ID
• org.apache.maven.archetypes
• Artifact_Id: maven-archetype-quickstart
Give the Group Id and Artifact Id(project
name) and finish
Project structure

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.

Building the Container Programmatically by Using


register(Class<?>… )
Spring Annotation Based Container
Configuration
❑ Starting from Spring 2.5 it became possible to configure the
dependency injection using annotations. So instead of using XML to
describe a bean wiring, you can move the bean configuration into the
component class itself by using annotations on the relevant class,
method, or field declaration.
**Why Spring Configuration with Annotations?
1.XML configuration can be verbose
2.Easy to configure your Spring beans with Annotations
3.Annotations minimize the XML configuration
Enable annotation-based wiring?
▪ Annotation wiring is not turned on in the Spring container by default. So,
before we can use annotation-based wiring, we will need to enable it in
our Spring configuration file. So consider the following configuration file in
case you want to use any annotation in your Spring application.
Spring Annotations
Spring provides to configure annotation-based metadata configuration:
• @Required
• @Autowired
• @Qualifier
• @primary
• @Resource
• @PostConstruct and @PreConstruct
• Note: All above annotations belong to stereotype
▪ @Required annotation is method-level annotation and applied to the setter
method of a bean. This annotation simply indicates that the setter method must
be configured to be dependency-injected with a value at configuration time.

• @Autowired is used to mark a dependency which Spring is going to


resolve and inject. We can use this annotation with a constructor,
setter, or field injection.
Create Maven Project
• In this project will create a maven project, in project, will implement
constructor based auto wiring, in which we are creating a message
based service.
• Constructor autowired
Create package service
• Inside service package create interface as MessageService :
Create a new package ServiceIMP
▪ Inside ServiceIMP package, create two classes and implement
MessageService interface in both the classes:
Create a new package config
• Create two classes AppConfig and ConstructorBasedInjection classes:
Main package
com.spring.DependencyInjection
@Primary Annotation
❑ Use @Primary to give higher preference to a bean when there are
multiple beans of the same type.
❑ In some cases, we need to register more than one bean of the same
type, at that we need to tell the container which one have highest
preferences.
• In the previous code, when we run :
• Spring throws NoUniqueBeanDefinitionException if we try to
run the application.

• To access beans with the same type we usually


use @Qualifier(“beanName”) annotation.
• We apply it at the injection point along with @Autowired. In our
case, we select the beans at the configuration phase
so @Qualifier can't be applied here.
• To resolve this issue Spring offers the @Primary annotation.

• We mark TonyEmployee() bean with @Primary.


• Spring will inject TonyEmployee() bean preferentially
• over the JohnEmployee().
Code Example (@Primary)(also make EmailService to
@primary and observe changes)
@Qualifier
We use @Qualifier annotation to resolve ambiguous dependencies.
1.Annotation helps fine-tune annotation-based autowiring. There may be
scenarios when we create more than one bean of the same type and
want to wire only one of them with a property. This can be controlled
using @Qualifier annotation along with the @Autowired annotation.
2.The @Qualifier is used to resolve ambiguous dependencies i.e, it helps
@Autowired annotations to choose one of the dependency.
Spring Bean Scope
When you create a bean definition what you are actually creating is a recipe for
creating actual instances of the class defined by that bean definition.
▪ Singleton: (Default) Scopes a single bean definition to a single object instance per
Spring IoC container
▪ Prototype: Scopes a single bean definition to any number of object instances.
▪ Request: Scopes a single bean definition to the lifecycle of a single HTTP request;
that is, each HTTP request has its own instance of a bean created off the back of a
single bean definition. Only valid in the context of a web-aware Spring
ApplicationContext.
▪ Session: Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid
in the context of a web-aware Spring ApplicationContext.
▪ Global Session- Scopes a single bean definition to the lifecycle of a global HTTP
session. It is valid when used in a portlet context. Only valid in the context of a web-
aware spring ApplicationContext.
Singleton Scoped
▪ 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.
Prototype scope
• non-singleton prototype scope of bean deployment results in the creation
of a new bean instance every time a request for that specific bean is made.
• Bean is injected into another bean or you request it through getBean().
Request, Session and Global session
• Used only in web-based applications, In order to support the scoping of beans at the
request, session and global session levels, minor initial configuration is required
before you can set about defining bean definitions.
a. Initial web configuration
• In order to support scoping of beans at the request, session, and global session levels
minor initial configuration is required before you can set about defining your bean
definitions.
b. The request scope
• Spring container will create a brand new instance of the LoginAction bean using the
'loginAction' bean definition for each and every HTTP request.
• 'loginAction' bean will be effectively scoped at the HTTP request level
Request, Session and Global session
c. The session scope
• Spring container will create a brand new instance of the
UserPreferences bean using the 'userPreferences' bean definition for
the lifetime of a single HTTP Session. The bean definition is as follows_

d. Global session scope


Global session scope is similar to standard HTTP session scope, and really only
makes sense in the context of portlet-based web applications. Portlet specification
defines notion of a global session that is shared amongst all the previous portlets
that makeup a single portlet web applications.
Code Structure
Prototype Code
• change the annotation Scope(“prototype”)
App.java would be same
Combining lifecycle mechanism
There are three option for controlling bean lifecycle behaviour:-
1. InitializingBean and DisposableBean callback interfaces
2. Custom init() and destroy() methods
3. @PostConstruct and PreDestroy annotations
When combining different lifecycle mechanism, following is the order
for initialization methods:-
▪ Methods annotated with @PostConstruct
▪ afterPropertiesSet() as defined by the InitializingBean callback
interface
▪ A custom configure init() method
Destroy methods
These method called in following order:-
• Methods annotated with @PreDestroy
• Destroy() as defined by the DisposableBean callback interface
• A custom configured destroy() method.
• Project Structure:
Add Spring dependency in POM.XML
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.0.RELEASE</version>
</dependency>

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;

• public class MyBean {


• @PreDestroy
• public void cleanup() {
• // Custom destruction logic here
• }
•}
BeanFactory or ApplicationContext
feature matrix that lists what features are provided by the BeanFactory and ApplicationContext
interfaces (and attendant implementations.
Review Questions
1. Discuss the concept of Inversion of Control.
2. What is Dependency Injection and Write some advantages of using
Dependency Injection?
3. Describe the Spring IoC container. What are its main responsibilities?
4. Write a code for simple Spring application using annotations to
configure beans and demonstrate dependency injection.
5. Discuss different Bean-scopes.
6. Write short notes on (a) Inversion of Control (b) Aspect Oriented
Programming.
7. What are the main concepts in Spring Framework?

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