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
https://notebookbft.wordpress.com/
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
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
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
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