SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Java Spring Framework
Java Spring FrameworkJava Spring Framework
Java Spring FrameworkMehul 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 frameworkRajiv Gupta
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVCDzmitry Naskou
 
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.2Rossen Stoyanchev
 
Spring framework
Spring frameworkSpring framework
Spring frameworkRajkumar 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 FrameworkRaveendra 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 ControlArjun Thakur
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootJosué 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 IoCFunnelll
 
Apache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolboxApache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolboxAntoine Sabot-Durand
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
OpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConOpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConos890
 

Was ist angesagt? (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
 

Ă„hnlich wie Introduction to Spring Framework Modules and Core Concepts

Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAOAnushaNaidu
 
2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdfDeoDuaNaoHet
 
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 depthVinay Kumar
 
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 BeansPawanMM
 
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 Basics
Spring BasicsSpring Basics
Spring BasicsDhaval Shah
 
Spring training
Spring trainingSpring training
Spring trainingshah_d_p
 
Skillwise-Spring framework 1
Skillwise-Spring framework 1Skillwise-Spring framework 1
Skillwise-Spring framework 1Skillwise 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 4than sare
 
Spring talk111204
Spring talk111204Spring talk111204
Spring talk111204ealio
 

Ă„hnlich wie Introduction to Spring Framework Modules and Core Concepts (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
 

KĂĽrzlich hochgeladen

Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfWilly Marroquin (WillyDevNET)
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 

KĂĽrzlich hochgeladen (20)

Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 

Introduction to Spring Framework Modules and Core Concepts

  • 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