SlideShare a Scribd company logo
Introduction to Spring
Rajind Ruparathna
AdroitLogic
Outline
● Introduction
● Framework Modules
● Spring Dependencies
● Dependency Injection
● The IoC Container
○ Spring IoC Container and Beans
○ XML-based Configuration Metadata
○ XML-based Beans
○ Instantiation of Beans
○ Dependency Injection
○ Bean Scopes
○ Depends On & Lazy-initialized Beans
○ Customizing the Nature of a Bean
○ Using PropertyPlaceholderConfigurer
2
Introduction
The Spring Framework is a Java platform that provides comprehensive
infrastructure support for developing Java applications. Spring handles the
infrastructure so you can focus on your application.
Spring enables you to build applications from "plain old Java objects" (POJOs)
and to apply enterprise services non-invasively to POJOs.
3
Framework Modules Overview
4
Spring Dependencies
Although Spring provides integration and support for a huge range of enterprise
and other external tools, it intentionally keeps its mandatory dependencies to an
absolute minimum.
To create an application context and use dependency injection to configure an
application we only need this.
5
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
Dependency Injection
Objects in an application have dependencies on each other. Using dependency
injection pattern we can remove dependency from the programming code.
Let's understand this with the following code. In this case, there is dependency
between the Employee and Address (tight coupling).
6
public class Employee {
private Address address;
public Employee() {
this.address = new Address();
}
}
Dependency Injection contd.
Thus, IOC makes the code loosely coupled. In such case, there is no need to
modify the code if our logic is moved to new environment.
7
public class Employee {
private Address address;
public Employee(Address address) {
this.address = address;
}
}
Dependency Injection contd.
In Spring framework, IOC container is responsible to inject the dependency. We
provide metadata to the IOC container either by XML file or annotation.
8
<?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:context="http://www.springframework.org/schema/context"
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">
<bean id="address" class="com.spring.model.Address">
<constructor-arg index="0" value="12345"/>
<constructor-arg index="1" value="Pirivena Rd"/>
</bean>
<bean id="employee" class="com.spring.model.Employee">
<constructor-arg name="address" ref="address"/>
</bean>
The IoC Container
https://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html
9
Spring IoC Container and Beans
Configuration metadata can be
XML based or Java based.
In this session we will only focus on
XML based configurations.
10
XML-based Configuration Metadata
Composing XML-based configuration metadata:
It can be useful to have bean definitions span multiple XML files. Often each
individual XML configuration file represents a logical layer or module in your
architecture. We can use one or more occurrences of the <import/> element to
load bean definitions from another file or files.
11
<beans>
<import resource="metrics/metrics.xml"/>
<import resource="management/management.xml"/>
<bean id="bean1" class="..."/>
<bean id="bean2" class="..."/>
</beans>
Using the Container
The ApplicationContext is the interface for an advanced factory capable of
maintaining a registry of different beans and their dependencies.
Using the method T getBean(String name, Class<T> requiredType)
you can retrieve instances of your beans. The ApplicationContext enables
you to read bean definitions and access them as follows:
12
// create and configure beans
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
// retrieve configured instance
Employee employee = context.getBean("employee", Employee.class);
// use configured instance
System.out.println("Lane: " + employee.getAddress().getLane());
XML-based Beans
Naming beans:
● Bean names start with a lowercase letter, and are camel-cased from then on.
Examples of such names would be (without quotes) 'accountManager',
'accountService', 'loginController', and so forth.
Aliasing a bean outside the bean definition:
Example:
13
<alias name="employee" alias="newNamedEmployee"/>
Instantiation of Beans
Constructor: When you create a bean by the constructor approach, all normal
classes are usable by and compatible with Spring.
That is, the class being developed does not need to implement any specific
interfaces or to be coded in a specific fashion. Simply specifying the bean class
should suffice. However, depending on what type of IoC you use for that specific
bean, you may need a default (empty) constructor.
14
Instantiation of Beans contd.
Static factory method: When defining a bean that you create with a static factory
method, you use the class attribute to specify the class containing the static
factory method and an attribute named factory-method to specify the name of the
factory method itself.
15
public class StaticServiceFactory {
private static ClientService clientService = new ClientService();
private static AccountService accountService = new AccountService();
private StaticServiceFactory() {}
public static ClientService createClientServiceInstance() {
return clientService;
}
public static AccountService createAccountServiceInstance() {
return accountService;
}
}
<bean id="clientService"
class="com.spring.service.StaticServiceFactory"
factory-method="createClientServiceInstance"/>
<bean id="accountService"
class="com.spring.service.StaticServiceFactory"
factory-method="createAccountServiceInstance"/>
Instantiation of Beans contd.
Instance factory method:
16
public class InstanceServiceFactory {
private static ClientService clientService = new ClientService();
private static AccountService accountService = new AccountService();
private InstanceServiceFactory() {}
public ClientService createClientServiceInstance() {
return clientService;
}
public AccountService createAccountServiceInstance() {
return accountService;
}
}
<bean id="instanceServiceFactory"
class="com.spring.service.InstanceServiceFactory"/>
<bean id="clientService" factory-bean="instanceServiceFactory"
factory-method="createClientServiceInstance"/>
<bean id="accountService" factory-bean="instanceServiceFactory"
factory-method="createAccountServiceInstance"/>
Dependency Injection
Constructor-based dependency injection:
Constructor-based DI is accomplished by the container invoking a constructor with
a number of arguments, each representing a dependency.
17
Dependency Injection contd.
Setter-based dependency
injection:
Setter-based DI is
accomplished by the
container calling setter
methods on your beans
after invoking a
no-argument constructor
18
Dependency Injection contd.
Setter-based dependency injection contd.
19
Dependencies and Configuration in Detail
Straight values (primitives, Strings, and so on):
The value attribute of the <property/> element specifies a property or
constructor argument as a human-readable string representation.
Spring’s conversion service is used to convert these values from a String to the
actual type of the property or argument.
20
Dependencies and Configuration in Detail contd.
The idref element:
The idref element is simply an error-proof way to pass the id (string value - not a
reference) of another bean in the container to a <constructor-arg/> or
<property/> element.
21
Dependencies and Configuration in Detail contd.
References to other beans (collaborators):
The ref element is the final element inside a <constructor-arg/> or
<property/> definition element. Here you set the value of the specified property
of a bean to be a reference to another bean (a collaborator) managed by the
container.
The referenced bean is a dependency of the bean whose property will be set, and
it is initialized on demand as needed before the property is set. (If the collaborator
is a singleton bean, it may be initialized already by the container.)
22
Dependencies and Configuration in Detail contd.
Inner beans:
A <bean/> element inside the <property/> or <constructor-arg/>
elements defines a so-called inner bean.The container also ignores the scope flag
on creation: Inner beans are always anonymous and they are always created with
the outer bean. It is not possible to to access them independently.
23
Dependencies and Configuration in Detail contd.
Collections:
In the <list/>, <set/>, <map/>,
and <props/> elements, you set
the properties and arguments of
the Java Collection types List, Set,
Map, and Properties, respectively.
24
Dependencies and Configuration in Detail contd.
Null and empty string values:
Spring treats empty arguments for properties and the like as empty Strings. The
following XML-based configuration metadata snippet sets the email property to the
empty String value ("").
The <null/> element handles null values.
25
Bean Scopes
The Singleton Scope: This is the default scope
26
Bean Scopes
The Prototype Scope:
27
Depends On
If a bean is a dependency of another that usually means that one bean is set as a
property of another.
Typically you accomplish this with the <ref/> element in XML-based
configuration metadata. However, sometimes dependencies between beans are
less direct.
28
Lazy-initialized Beans
By default, Spring eagerly create and configure all singleton beans as part of the
initialization process.
Generally, this pre-instantiation is desirable, because errors in the configuration or
surrounding environment are discovered immediately, as opposed to hours or
even days later. When this behavior is not desirable, you can prevent
pre-instantiation of a singleton bean by marking the bean definition as
lazy-initialized. A lazy-initialized bean tells the IoC container to create a bean
instance when it is first requested, rather than at startup.
29
Customizing the Nature of a Bean
Initialization
callbacks:
Destruction
callbacks:
30
Using PropertyPlaceholderConfigurer
By default, Spring eagerly create and configure all singleton beans as part of the
initialization process.
Generally, this pre-instantiation is desirable, because errors in the configuration or
surrounding environment are discovered immediately, as opposed to hours or
even days later. When this behavior is not desirable, you can prevent
pre-instantiation of a singleton bean by marking the bean definition as
lazy-initialized. A lazy-initialized bean tells the IoC container to create a bean
instance when it is first requested, rather than at startup.
31
Using PropertyPlaceholderConfigurer
jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://production:9002
jdbc.username=sa
jdbc.password=root
32
References
https://docs.spring.io/spring/docs/current/spring-framework-reference/html/overvie
w.html
https://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.h
tml
33

More Related Content

What's hot

Java Spring Framework
Java Spring FrameworkJava Spring Framework
Java Spring Framework
Mehul Jariwala
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Serhat Can
 
Spring bean mod02
Spring bean mod02Spring bean mod02
Spring bean mod02Guo Albert
 
Java spring framework
Java spring frameworkJava spring framework
Java spring framework
Rajiv Gupta
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
Dzmitry Naskou
 
Spring 4 Web App
Spring 4 Web AppSpring 4 Web App
Spring 4 Web App
Rossen Stoyanchev
 
Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2
Rossen Stoyanchev
 
Spring framework
Spring frameworkSpring framework
Spring framework
Rajkumar Singh
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Raveendra R
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Arjun Thakur
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
Josué Neis
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
Funnelll
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Hùng Nguyễn Huy
 
Apache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolboxApache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolbox
Antoine Sabot-Durand
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
Dzmitry Naskou
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
Hamid Ghorbani
 
Spring Framework Training Course
Spring Framework Training Course Spring Framework Training Course
Spring Framework Training Course
RMS Software Technologies
 
OpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConOpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheCon
os890
 

What's hot (19)

Java Spring Framework
Java Spring FrameworkJava Spring Framework
Java Spring Framework
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring bean mod02
Spring bean mod02Spring bean mod02
Spring bean mod02
 
Java spring framework
Java spring frameworkJava spring framework
Java spring framework
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
Spring 4 Web App
Spring 4 Web AppSpring 4 Web App
Spring 4 Web App
 
Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Apache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolboxApache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolbox
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
 
Spring Framework Training Course
Spring Framework Training Course Spring Framework Training Course
Spring Framework Training Course
 
OpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConOpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheCon
 

Similar to Introduction to Spring Framework

Spring core
Spring coreSpring core
Spring core
Harshit Choudhary
 
Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAO
AnushaNaidu
 
2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf
DeoDuaNaoHet
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questionsDhiraj Champawat
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
Vinay Kumar
 
Spring
SpringSpring
Spring
gauravashq
 
Spring
SpringSpring
Spring
gauravashq
 
Spring
SpringSpring
Spring
gauravashq
 
Spring by rj
Spring by rjSpring by rj
Session 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI BeansSession 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI Beans
PawanMM
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Michał Orman
 
Spring design-juergen-qcon
Spring design-juergen-qconSpring design-juergen-qcon
Spring design-juergen-qconYiwei Ma
 
Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample
Sunil kumar Mohanty
 
Spring Fa Qs
Spring Fa QsSpring Fa Qs
Spring Fa Qsjbashask
 
Spring training
Spring trainingSpring training
Spring trainingshah_d_p
 
Skillwise-Spring framework 1
Skillwise-Spring framework 1Skillwise-Spring framework 1
Skillwise-Spring framework 1
Skillwise Group
 
Spring framework
Spring frameworkSpring framework
Spring frameworkAjit Koti
 
Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4
than sare
 
Spring talk111204
Spring talk111204Spring talk111204
Spring talk111204
ealio
 

Similar to Introduction to Spring Framework (20)

Spring core
Spring coreSpring core
Spring core
 
Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAO
 
2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
 
Spring
SpringSpring
Spring
 
Spring
SpringSpring
Spring
 
Spring
SpringSpring
Spring
 
Spring by rj
Spring by rjSpring by rj
Spring by rj
 
Session 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI BeansSession 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI Beans
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1
 
Spring design-juergen-qcon
Spring design-juergen-qconSpring design-juergen-qcon
Spring design-juergen-qcon
 
Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample Spring IOC advantages and developing spring application sample
Spring IOC advantages and developing spring application sample
 
Spring Fa Qs
Spring Fa QsSpring Fa Qs
Spring Fa Qs
 
Spring Basics
Spring BasicsSpring Basics
Spring Basics
 
Spring training
Spring trainingSpring training
Spring training
 
Skillwise-Spring framework 1
Skillwise-Spring framework 1Skillwise-Spring framework 1
Skillwise-Spring framework 1
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4
 
Spring talk111204
Spring talk111204Spring talk111204
Spring talk111204
 

Recently uploaded

Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 

Recently uploaded (20)

Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 

Introduction to Spring Framework

  • 1. Introduction to Spring Rajind Ruparathna AdroitLogic
  • 2. Outline ● Introduction ● Framework Modules ● Spring Dependencies ● Dependency Injection ● The IoC Container ○ Spring IoC Container and Beans ○ XML-based Configuration Metadata ○ XML-based Beans ○ Instantiation of Beans ○ Dependency Injection ○ Bean Scopes ○ Depends On & Lazy-initialized Beans ○ Customizing the Nature of a Bean ○ Using PropertyPlaceholderConfigurer 2
  • 3. Introduction The Spring Framework is a Java platform that provides comprehensive infrastructure support for developing Java applications. Spring handles the infrastructure so you can focus on your application. Spring enables you to build applications from "plain old Java objects" (POJOs) and to apply enterprise services non-invasively to POJOs. 3
  • 5. Spring Dependencies Although Spring provides integration and support for a huge range of enterprise and other external tools, it intentionally keeps its mandatory dependencies to an absolute minimum. To create an application context and use dependency injection to configure an application we only need this. 5 <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency>
  • 6. Dependency Injection Objects in an application have dependencies on each other. Using dependency injection pattern we can remove dependency from the programming code. Let's understand this with the following code. In this case, there is dependency between the Employee and Address (tight coupling). 6 public class Employee { private Address address; public Employee() { this.address = new Address(); } }
  • 7. Dependency Injection contd. Thus, IOC makes the code loosely coupled. In such case, there is no need to modify the code if our logic is moved to new environment. 7 public class Employee { private Address address; public Employee(Address address) { this.address = address; } }
  • 8. Dependency Injection contd. In Spring framework, IOC container is responsible to inject the dependency. We provide metadata to the IOC container either by XML file or annotation. 8 <?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:context="http://www.springframework.org/schema/context" 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"> <bean id="address" class="com.spring.model.Address"> <constructor-arg index="0" value="12345"/> <constructor-arg index="1" value="Pirivena Rd"/> </bean> <bean id="employee" class="com.spring.model.Employee"> <constructor-arg name="address" ref="address"/> </bean>
  • 10. Spring IoC Container and Beans Configuration metadata can be XML based or Java based. In this session we will only focus on XML based configurations. 10
  • 11. XML-based Configuration Metadata Composing XML-based configuration metadata: It can be useful to have bean definitions span multiple XML files. Often each individual XML configuration file represents a logical layer or module in your architecture. We can use one or more occurrences of the <import/> element to load bean definitions from another file or files. 11 <beans> <import resource="metrics/metrics.xml"/> <import resource="management/management.xml"/> <bean id="bean1" class="..."/> <bean id="bean2" class="..."/> </beans>
  • 12. Using the Container The ApplicationContext is the interface for an advanced factory capable of maintaining a registry of different beans and their dependencies. Using the method T getBean(String name, Class<T> requiredType) you can retrieve instances of your beans. The ApplicationContext enables you to read bean definitions and access them as follows: 12 // create and configure beans ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml"); // retrieve configured instance Employee employee = context.getBean("employee", Employee.class); // use configured instance System.out.println("Lane: " + employee.getAddress().getLane());
  • 13. XML-based Beans Naming beans: ● Bean names start with a lowercase letter, and are camel-cased from then on. Examples of such names would be (without quotes) 'accountManager', 'accountService', 'loginController', and so forth. Aliasing a bean outside the bean definition: Example: 13 <alias name="employee" alias="newNamedEmployee"/>
  • 14. Instantiation of Beans Constructor: When you create a bean by the constructor approach, all normal classes are usable by and compatible with Spring. That is, the class being developed does not need to implement any specific interfaces or to be coded in a specific fashion. Simply specifying the bean class should suffice. However, depending on what type of IoC you use for that specific bean, you may need a default (empty) constructor. 14
  • 15. Instantiation of Beans contd. Static factory method: When defining a bean that you create with a static factory method, you use the class attribute to specify the class containing the static factory method and an attribute named factory-method to specify the name of the factory method itself. 15 public class StaticServiceFactory { private static ClientService clientService = new ClientService(); private static AccountService accountService = new AccountService(); private StaticServiceFactory() {} public static ClientService createClientServiceInstance() { return clientService; } public static AccountService createAccountServiceInstance() { return accountService; } } <bean id="clientService" class="com.spring.service.StaticServiceFactory" factory-method="createClientServiceInstance"/> <bean id="accountService" class="com.spring.service.StaticServiceFactory" factory-method="createAccountServiceInstance"/>
  • 16. Instantiation of Beans contd. Instance factory method: 16 public class InstanceServiceFactory { private static ClientService clientService = new ClientService(); private static AccountService accountService = new AccountService(); private InstanceServiceFactory() {} public ClientService createClientServiceInstance() { return clientService; } public AccountService createAccountServiceInstance() { return accountService; } } <bean id="instanceServiceFactory" class="com.spring.service.InstanceServiceFactory"/> <bean id="clientService" factory-bean="instanceServiceFactory" factory-method="createClientServiceInstance"/> <bean id="accountService" factory-bean="instanceServiceFactory" factory-method="createAccountServiceInstance"/>
  • 17. Dependency Injection Constructor-based dependency injection: Constructor-based DI is accomplished by the container invoking a constructor with a number of arguments, each representing a dependency. 17
  • 18. Dependency Injection contd. Setter-based dependency injection: Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor 18
  • 19. Dependency Injection contd. Setter-based dependency injection contd. 19
  • 20. Dependencies and Configuration in Detail Straight values (primitives, Strings, and so on): The value attribute of the <property/> element specifies a property or constructor argument as a human-readable string representation. Spring’s conversion service is used to convert these values from a String to the actual type of the property or argument. 20
  • 21. Dependencies and Configuration in Detail contd. The idref element: The idref element is simply an error-proof way to pass the id (string value - not a reference) of another bean in the container to a <constructor-arg/> or <property/> element. 21
  • 22. Dependencies and Configuration in Detail contd. References to other beans (collaborators): The ref element is the final element inside a <constructor-arg/> or <property/> definition element. Here you set the value of the specified property of a bean to be a reference to another bean (a collaborator) managed by the container. The referenced bean is a dependency of the bean whose property will be set, and it is initialized on demand as needed before the property is set. (If the collaborator is a singleton bean, it may be initialized already by the container.) 22
  • 23. Dependencies and Configuration in Detail contd. Inner beans: A <bean/> element inside the <property/> or <constructor-arg/> elements defines a so-called inner bean.The container also ignores the scope flag on creation: Inner beans are always anonymous and they are always created with the outer bean. It is not possible to to access them independently. 23
  • 24. Dependencies and Configuration in Detail contd. Collections: In the <list/>, <set/>, <map/>, and <props/> elements, you set the properties and arguments of the Java Collection types List, Set, Map, and Properties, respectively. 24
  • 25. Dependencies and Configuration in Detail contd. Null and empty string values: Spring treats empty arguments for properties and the like as empty Strings. The following XML-based configuration metadata snippet sets the email property to the empty String value (""). The <null/> element handles null values. 25
  • 26. Bean Scopes The Singleton Scope: This is the default scope 26
  • 28. Depends On If a bean is a dependency of another that usually means that one bean is set as a property of another. Typically you accomplish this with the <ref/> element in XML-based configuration metadata. However, sometimes dependencies between beans are less direct. 28
  • 29. Lazy-initialized Beans By default, Spring eagerly create and configure all singleton beans as part of the initialization process. Generally, this pre-instantiation is desirable, because errors in the configuration or surrounding environment are discovered immediately, as opposed to hours or even days later. When this behavior is not desirable, you can prevent pre-instantiation of a singleton bean by marking the bean definition as lazy-initialized. A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup. 29
  • 30. Customizing the Nature of a Bean Initialization callbacks: Destruction callbacks: 30
  • 31. Using PropertyPlaceholderConfigurer By default, Spring eagerly create and configure all singleton beans as part of the initialization process. Generally, this pre-instantiation is desirable, because errors in the configuration or surrounding environment are discovered immediately, as opposed to hours or even days later. When this behavior is not desirable, you can prevent pre-instantiation of a singleton bean by marking the bean definition as lazy-initialized. A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup. 31