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 (19)

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

Similar to Introduction to Spring Framework (20)

PPT
Spring
s4al_com
 
PPT
Spring talk111204
s4al_com
 
PPT
Spring talk111204
ealio
 
PPT
SpringIntroductionpresentationoverintroduction.ppt
imjdabhinawpandey
 
PPT
Spring introduction
AnilKumar Etagowni
 
PDF
2-0. Spring ecosytem.pdf
DeoDuaNaoHet
 
PPTX
Spring (1)
Aneega
 
PPTX
Spring framework IOC and Dependency Injection
Anuj Singh Rajput
 
PPT
Spring frame work
husnara mohammad
 
PPTX
Introduction to Spring Framework
Dineesha Suraweera
 
PPTX
Skillwise-Spring framework 1
Skillwise Group
 
PPT
Spring framework
Ajit Koti
 
PDF
Manual tutorial-spring-java
sagicar
 
PDF
Spring Reference
asas
 
PPTX
Spring Framework Essentials
Edward Goikhman
 
PPT
Hybernat and structs, spring classes in mumbai
Vibrant Technologies & Computers
 
PDF
Spring Reference
Syed Shahul
 
PPTX
Spring framework
Sonal Poddar
 
ODT
Spring IOC advantages and developing spring application sample
Sunil kumar Mohanty
 
Spring
s4al_com
 
Spring talk111204
s4al_com
 
Spring talk111204
ealio
 
SpringIntroductionpresentationoverintroduction.ppt
imjdabhinawpandey
 
Spring introduction
AnilKumar Etagowni
 
2-0. Spring ecosytem.pdf
DeoDuaNaoHet
 
Spring (1)
Aneega
 
Spring framework IOC and Dependency Injection
Anuj Singh Rajput
 
Spring frame work
husnara mohammad
 
Introduction to Spring Framework
Dineesha Suraweera
 
Skillwise-Spring framework 1
Skillwise Group
 
Spring framework
Ajit Koti
 
Manual tutorial-spring-java
sagicar
 
Spring Reference
asas
 
Spring Framework Essentials
Edward Goikhman
 
Hybernat and structs, spring classes in mumbai
Vibrant Technologies & Computers
 
Spring Reference
Syed Shahul
 
Spring framework
Sonal Poddar
 
Spring IOC advantages and developing spring application sample
Sunil kumar Mohanty
 
Ad

Recently uploaded (20)

PPTX
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PPTX
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PDF
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
PPTX
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PDF
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PPTX
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PDF
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
Ad

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