0% found this document useful (0 votes)
16 views99 pages

Session 03 Spring Framework

The document provides an overview of the Spring Framework, detailing its modular structure, benefits, and key components such as the IoC container and Dependency Injection. It also covers Spring Boot, emphasizing its role in simplifying the development of microservices and reducing configuration complexity. Additionally, the document discusses Spring annotations and bean lifecycle management, along with practical examples for creating Spring applications.

Uploaded by

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

Session 03 Spring Framework

The document provides an overview of the Spring Framework, detailing its modular structure, benefits, and key components such as the IoC container and Dependency Injection. It also covers Spring Boot, emphasizing its role in simplifying the development of microservices and reducing configuration complexity. Additionally, the document discusses Spring annotations and bean lifecycle management, along with practical examples for creating Spring applications.

Uploaded by

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

Session 01

ANTEA TRAINING
Spring Framework
Session 03
• Summary
• The Spring Framework overview

• The Application Context and Dependency Injection

• Spring Configuration and Scanning

• Spring Boot
Session 02

Spring Framework Overview


Session 03
Spring Framework
• What is Spring Framework?
• The Spring Framework provides a comprehensive
programming and configuration model for modern Java-
based enterprise applications.
• Spring is a lightweight framework. 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.
• Spring framework targets to make J2EE development easier
to use and promotes good programming practices by
enabling a POJO-based programming model.
Spring Framework
• Benefits of Using Spring Framework?
• Spring enables developers to develop enterprise-class applications
using POJOs classes.
• Spring is organized in a modular fashion.
• Spring integrates many famous technologies for you like several ORM
frameworks, logging frameworks, JEE, Quartz and JDK timers, and other
view technologies.
• Spring helps you to test your application code.
• Spring's web framework is a well-designed web MVC framework.
• Spring provides a convenient API to translate technology-specific
exceptions into consistent, unchecked exceptions.
• Lightweight IoC containers tend to be lightweight, especially when
compared to EJB containers.
• Spring provides a consistent transaction management interface.
Spring Framework
• Keys Advantages of Spring Framework?

1) Predefined Templates  JDBC, Hibernate, JPA etc.


2) Loose Coupling  dependency injection.
3) Easy to test  doesn't require server.
4) Lightweight  less than 2mb.
5) Fast Development  support to various frameworks.
6) Powerful abstraction  JMS, JDBC, JPA and JTA.
7) Declarative support  Works with Annotations.
Spring Framework
• Spring Modules?
Spring Framework
• Spring Core Container Module
• The Core Container consists of the Core, Beans, Context, and
Expression Language modules the details of which are as follows −
• The Core module provides the fundamental parts of the
framework, including the IoC and Dependency Injection features.
• The Bean module provides BeanFactory, which is a sophisticated
implementation of the factory pattern.
• The Context module builds on the solid base provided by the Core
and Beans modules and it is a medium to access any objects
defined and configured. The ApplicationContext interface is the
focal point of the Context module.
• The SpEL module provides a powerful expression language for
querying and manipulating an object graph at runtime.
Spring Framework
• Spring Data Access/Integration Module
• The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS
and Transaction modules whose detail is as follows −
• The JDBC module provides a JDBC-abstraction layer that removes the
need for tedious JDBC related coding.
• The ORM module provides integration layers for popular object-relational
mapping APIs, including JPA, JDO, Hibernate, and iBatis.
• The OXM module provides an abstraction layer that supports Object/XML
mapping implementations for JAXB, Castor, XMLBeans, JiBX and XStream.
• The Java Messaging Service JMS module contains features for producing
and consuming messages.
• The Transaction module supports programmatic and declarative
transaction management for classes that implement special interfaces
and for all your POJOs.
Spring Framework
• Spring Web Module
• The Web layer consists of the Web, Web-MVC, Web-Socket, and Web-
Portlet modules the details of which are as follows −
• The Web module provides basic web-oriented integration features such
as multipart file-upload functionality and the initialization of the IoC
container using servlet listeners and a web-oriented application
context.
• The Web-MVC module contains Spring's Model-View-Controller (MVC)
implementation for web applications.
• The Web-Socket module provides support for WebSocket-based, two-
way communication between the client and the server in web
applications.
• The Web-Portlet module provides the MVC implementation to be used
in a portlet environment and mirrors the functionality of Web-Servlet
module.
Spring Framework
• Spring Miscellaneous Modules
• There are few other important modules like AOP, Aspects, Instrumentation,
Web and Test modules the details of which are as follows −
• The AOP module provides an aspect-oriented programming implementation
allowing you to define method-interceptors and pointcuts to cleanly
decouple code that implements functionality that should be separated.
• The Aspects module provides integration with AspectJ, which is again a
powerful and mature AOP framework.
• The Instrumentation module provides class instrumentation support and
class loader implementations to be used in certain application servers.
• The Messaging module provides support for STOMP as the WebSocket sub-
protocol to use in applications. It also supports an annotation programming
model for routing and processing STOMP messages from WebSocket clients.
• The Test module supports the testing of Spring components with JUnit or
TestNG frameworks.
Spring Framework
• Spring Example Application

Create the our first spring application :


1. Create the class
2. Create the xml file to provide the values
3. Create the test class
4. Load the spring jar files
5. Run the test class
Spring Framework
• Spring Example Application
Spring Framework
• Spring Example Application
Spring Framework
• Spring Example Application
Spring Framework
• Spring Example Application
• There are mainly three jar files required to run this application.

• org.springframework.core-3.0.1.RELEASE-A

• com.springsource.org.apache.commons.logging-1.1.1

• org.springframework.beans-3.0.1.RELEASE-A

• Forthe future use, we will use maven to download


automatically the required jars to our spring application.
Spring Framework
• Spring Example Application
Session 02

The Application Context and IoC


Session 03
Spring Framework
• Reminder : Inversion Of Control Design Pattern:

•A pattern often seen in Web Applications, the Service Locator


pattern is used to decouple the Service Consumers and the
concrete classes like DAO implementations.
• The pattern looks for the adequate service, saves it in cache
storage to reduce the number of requests and therefore the
strain on the server and provides the application with their
instances.
• The inversion of control pattern is also known as service
locator pattern.
JEE Design Pattern
• Service Locator Design Pattern:
Spring Framework
• Spring IoC Container:
• The IoC container is responsible to instantiate, configure and
assemble the objects.
• The IoC container gets information's from the XML file and
works accordingly.
• BeanFactory

• ApplicationContext
• AOP
• message
• resource handling
Spring Framework
• 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.
• Insuch case we provide the information from the external
source such as XML file.
• It makes our code loosely coupled and easier for testing.

• Dependency Injection by constructor

• Dependency Injection by setter method


Spring Framework
• Dependency Injection by Constructor:
Spring Framework
• Dependency Injection by Constructor:
Spring Framework
• Dependency Injection by Constructor:
Spring Framework
• Dependency Injection by Constructor:
Spring Framework
• Dependency Injection by setter method:
Spring Framework
• Dependency Injection by setter method:
Spring Framework
• Constructor Injection with Dependent Object:
Spring Framework
• Constructor Injection with Dependent Object:
Spring Framework
• Constructor Injection with Dependent Object:
Spring Framework
• Autowiring in Spring:

• Autowiring feature of spring framework enables you to inject


the object dependency implicitly. It internally uses setter or
constructor injection with references only.
• There are many autowiring modes:

• 1) no
• 2) byName
• 3) byType
• 4) constructor
• 5) autodetect (Deprecated)
Spring Framework
• Autowiring in Spring:
Spring Framework
• Autowiring in Spring:

• byName autowiring mode

• byType autowiring mode


Spring Framework
• Autowiring in Spring:

• constructor autowiring mode

• no autowiring mode
Session 02

Spring Configuration classes


Session 03
Spring Framework
• 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 slides.
Spring Framework
• Spring - Bean Definition:

This attribute is mandatory and specifies the bean class to be used to create the
class
bean

This attribute specifies the bean identifier uniquely. In XMLbased configuration


name
metadata, you use the id and/or name attributes to specify the bean identifier(s).

This attribute specifies the scope of the objects created from a particular bean
scope
definition.

constructor-arg This is used to inject the dependencies.

properties This is used to inject the dependencies.

autowiring mode This is used to inject the dependencies.

lazy-initialization A lazy-initialized bean tells the IoC container to create a bean instance when it is
mode first requested, rather than at the startup.

A callback to be called just after all necessary properties on the bean have been
initialization method set by the container.

destruction method A callback to be used when the container containing the bean is destroyed.
Spring Framework
• Spring - Bean Scopes:
• The scope of a bean defines the life cycle and visibility of that
bean in the contexts we use it.
• The latest version of the Spring framework defines 6 types of
scopes:
• singleton

• prototype

• Request (web application)

• Session (web application)

• Application (web application)

• Websocket (web application)


Spring Framework
• Spring - Bean Scopes:
• When we define a bean with the singleton scope, the
container creates a single instance of that bean; all requests
for that bean name will return the same object, which is
cached.
• Any modifications to the object will be reflected in all
references to the bean. This scope is the default value if no
other scope is specified.
Spring Framework
• Spring - Bean Scopes:
•A bean with the prototype scope will return a different
instance every time it is requested from the container.
• It is defined by setting the value prototype to
the @Scope annotation in the bean definition
Spring Framework
• Spring - Bean Scopes: Request Scope
• We can define the bean with the request scope using
the @RequestScope annotation:
Spring Framework
• Spring - Bean lifecycle :
• The lifecycle of any object refers to when & how the bean is
instantiated, what action it performs until it lives, and when &
how it is destroyed.
• init()
method to execute all its code as the spring container
starts up and the bean is instantiated, and destroy() method
to execute all its code on closing the container.
Spring Framework
• Spring - Bean lifecycle : Using Annotation
• To provide the facility to the created bean to invoke
custom init() method on the startup of a spring container and
to invoke the custom destroy() method on closing the
container, we need annotate init() method
by @PostConstruct annotation and destroy() method
by @PreDestroy annotation.
Spring Framework
• Spring - Bean lifecycle : Using Annotation
Session 02

Spring Bean Annotations


Session 03
Spring Framework
• Spring - Bean Annotations:
• There're several ways to configure beans in a Spring container.

• We can declare them using XML configuration.

• We can declare beans using the @Bean annotation in a


configuration class.
• Or we can mark the class with one of the annotations from
the org.springframework.stereotype package.
Spring Framework
• Spring - Bean Annotations:
• @ComponentScan configures which packages to scan for
classes with annotation configuration.
• We can specify the base package names directly or we can
point to classes also.
Spring Framework
• Spring - Bean Annotations:
• @Component is a class level annotation. During the
component scan, Spring Framework automatically detects
classes annotated with @Component.

• Since @Repository, @Service, @Configuration,


and @Controller are all meta-annotations of @Component,
they share the same bean naming behavior.
Spring Framework
• Spring - Bean Annotations:
• @Repository DAO or Repository classes usually represent the
database access layer in an application, and should be
annotated with @Repository:
Spring Framework
• Spring - Bean Annotations:
• @Service The business logic of an application usually resides
within the service layer – so we'll use
the @Service annotation to indicate that a class belongs to
that layer:
Spring Framework
• Spring - Bean Annotations:
• @Controlleris a class level annotation which tells the Spring
Framework that this class serves as a controller in Spring
MVC:
Spring Framework
• Spring - Bean Annotations:
• @Configuration Configuration classes can contain bean
definition methods annotated with @Bean:
Session 03

Spring Boot
Session 03
Spring Boot
• Spring Boot introduction:
• Spring Boot is an open source Java-based framework used to
create a micro Service.
• Micro Service is an architecture that allows the developers to
develop and deploy services independently.
• Each service running has its own process and this achieves
the lightweight model to support business applications.
• Spring Boot provides a good platform for Java developers to
develop a stand-alone and production-grade spring
application based on micro services architecture.
Spring Boot
• Spring Boot introduction:
• Advantages :
• Easy to understand and develop spring applications
• Increases productivity
• Reduces the development time
• Goals:
• To avoid complex XML configuration in Spring
• To develop a production ready Spring applications in an easier
way
• To reduce the development time and run the application
independently
• Offer an easier way of getting started with the application
Spring Boot
• Why Spring Boot ?
• It
provides a flexible way to configure Java Beans, XML
configurations, and Database Transactions.
• It
provides a powerful batch processing and manages REST
endpoints.
• InSpring Boot, everything is auto configured; no manual
configurations are needed.
• It offers annotation-based spring application

• Eases dependency management

• It includes Embedded Servlet Container


Spring Boot
• How Spring Boot works ?
Spring Boot
• How Spring Boot works ?
• Presentation Layer: The presentation layer handles the HTTP
requests, translates the JSON parameter to object, and
authenticates the request and transfer it to the business layer. In
short, it consists of views i.e., frontend part.
• Business Layer: The business layer handles all the business logic.
It consists of service classes and uses services provided by data
access layers. It also performs authorization and validation.
• Persistence Layer: The persistence layer contains all the storage
logic and translates business objects from and to database rows.
• Database Layer: In the database layer, CRUD (create, retrieve,
update, delete) operations are performed.
Spring Boot
• How Spring Boot works ?
Spring Boot
• Spring Initializr:

• https://start.spring.io/
is a web-based tool provided by the
Pivotal Web Service. With the help of Spring Initializr, we can
easily generate the structure of the Spring Boot Project.
• It offers extensible API for creating JVM-based projects.

• It supports IntelliJ IDEA Ultimate, NetBeans, Eclipse.


Spring Boot
• Spring Initializr:
Spring Boot
• Spring Boot Annotations:

• @EnableAutoConfiguration: It auto-configures the bean that


is present in the classpath and configures it to run the
methods.
• The use of this annotation is reduced in Spring Boot 1.2.0
release because developers provided an alternative of the
annotation, i.e. @SpringBootApplication.
• @SpringBootApplication: It is a combination of three
annotations @EnableAutoConfiguration,
@ComponentScan, and @Configuration.
Spring Boot
• Spring Boot Sample:
Spring Boot
• Spring Boot Dependency Management:

• SpringBoot manages dependencies and configuration


automatically using with Maven.
• It
provides the centralization of dependency information by
specifying the Spring Boot version in one place.
• Itavoids mismatch of different versions of Spring Boot
libraries.
• We only need to write a library name with specifying the
version. It is helpful in multi-module projects.
Spring Boot
• Spring Boot Dependency Management:

• The following spring-boot-starter-parent inherits


automatically when we configure the project.

• We can also add Maven plugin in our pom.xml file. It wraps


the project into an executable jar file.
Spring Boot
• Spring Boot Application Properties:

• Spring Boot Framework comes with a built-in mechanism for


application configuration using a file
called application.properties.
Spring Boot
• Spring Boot Application Properties:

• Thefollowing tables provide a list of common Spring Boot


properties:
Property Default Description

Debug false It enables debug logs.

spring.application. It is used to set the application name.


name
server.port 8080 Configures the HTTP server port

logging.file.path It configures the location of the log file.

logging.file It is used to set log file name. For example, data.log.

server.address It is used to set network address to which the server


should bind to.
server.ssl.enabled It is used to enable SSL support.
Spring Boot
• Spring Boot Code Structure:
• Spring
Boot does not have any code layout to work with.
However, there are some best practices that will help us.
Spring Boot
• Spring Boot Building RESTful Web Services :
• Spring
Boot provides a very good support to building RESTful
Web Services for enterprise applications.
• Forbuilding a RESTful Web Services, we need to add the
Spring Boot Starter Web dependency into the build
configuration file pom.xml maven file :
Spring Boot
• Spring Boot Building RESTful Web Services :
• The
@RestController annotation is used to define the RESTful
web services. It serves JSON, XML and custom response.

• The@RequestMapping annotation is used to define the


Request URI to access the REST Endpoints.
Spring Boot
• Spring Boot Building RESTful Web Services :
• The@RequestBody annotation is used to define the request
body content type.

• The@PathVariable annotation is used to define the custom


or dynamic request URI.

• The@RequestParam annotation is used to read the request


parameters from the Request URL.
Spring Boot
• Spring Boot Building RESTful Web Services :
• The default HTTP request method is GET. This method does
not require any Request Body.
Spring Boot
• Spring Boot Building RESTful Web Services :
• TheHTTP POST request is used to create a resource. This
method contains the Request Body.
Spring Boot
• Spring Boot Building RESTful Web Services :
• The HTTP PUT request is used to update the existing
resource. This method contains a Request Body.
Spring Boot
• Spring Boot Building RESTful Web Services :
• The HTTP Delete request is used to delete the existing
resource. This method does not contain any Request Body.
Session 03

Spring Security
Session 03
Spring Security
• Spring Security Introduction:
• Spring Security is a framework which provides various
security features like: authentication, authorization to create
secure Java Enterprise Applications.
• Authorization is
the process to allow authority to perform
actions in the application. We can apply authorization to
authorize web request, methods and access to individual
domain.
• Thebeauty of this framework is its flexible authentication
nature to integrate with any software solution.
• HTTP BASIC, LDAP, OpenID, Kerberos, Oauth2 …
Spring Security
• Spring Security Advantages :
• Comprehensive support for authentication and authorization.
• Protection against common tasks
• Servlet API integration
• Integration with Spring MVC
• Portability
• CSRF protection
• Java Configuration support
Spring Security
• Spring Project Modules:
• spring-security-core.jar
• spring-security-remoting.jar
• spring-security-web.jar
• spring-security-config.jar
• spring-security-ldap.jar
• spring-security-oauth2-*.jar (JWT)
• spring-security-acl.jar (Security Access Control List)
• spring-security-cas.jar (Central Authentication Service, SSO)
• spring-security-openid.jar
• spring-security-test.jar
Spring Security
• Spring Security Project : Create Spring Security Java configuration
Spring Security
• SpringSecurity Project : register the springSecurityFilterChain
for every URL in our application.
• To register, Spring Security provides a base class
AbstractSecurityWebApplicationInitializer that we need to
extend.
Spring Security
• Spring Security Project : load WebSecurityConfig in our existing
ApplicationInitializer and add into the getRootConfigClasses()
method.
Spring Security
• Spring Security Project : WebSecurityConfigurerAdapter class
provides a configure(HttpSecurity http) method that contains
the following default configuration.
Spring Security
• SpringSecurity Project : Creating a controller to handle user
requests.
Spring Security
• Spring Security Project : Test our application.
Spring Security
• Spring Security Project : Test our application.
Session 03

Testing with Spring + JUnit


Session 03
Spring Test
• Spring Test Framework:
• Testing is an integral part of enterprise software
development.
• The Spring Framework help us to perform tests using Spring
Test and Spring Boot features to test the interactions
between Spring and your code.
Spring Test
• Spring Test Framework :
• Starting with Spring Initializr
Spring Test
• Spring Test Framework :
• Create a Simple Application
Spring Test
• Spring Test Framework :
• Run the Application
Spring Test
• Spring Test Framework :
• The first thing we can create a simple sanity check test that
will fail if the application context cannot start.
Spring Test
• Spring Test Framework :
• Wecan check if our controller is loaded and he is retuning
something.
Spring Test
• Spring Test Framework :
• Wecan check if our controller is loaded and he is retuning
something.
Spring Test
• Spring Test Framework :
• A mock service imitates a real REST or SOAP API – it contains
definitions for operations that clients call, receives requests,
and returns simulated responses.
• Injecting a mock is a clean way to introduce such isolation.
To do that, use Spring’s MockMvc and ask for that to be injected for you by using the @AutoConfigureMockMvc annotation on the test case.

Spring Test
• Spring Test Framework :

• Wecan use Spring’s MockMvc and inject it using the


@AutoConfigureMockMvc annotation on the test case.
Responsible Name of the document manager
File name Session 03 Spring Framework.pptx
Revisions
R01 Data rev. Farouk Korteby Creation of the document

This document is © 2021 Antea s.r.l.

You might also like