Lesson 7 - Introduction To Spring
Lesson 7 - Introduction To Spring
Application Layer
Data
Client Layer Server Business Data
Access
Layer Layer
Layer
Presentation Layer
Shortcomings of the Java EE Architecture
• Java EE specifications don’t help in understanding the implementation of the specification and the
environment.
• The components in the architecture are written in a way that only the container can understand or handle
them.
Why Spring?
• Spring is a framework that can help simplify the Java EE architecture by reducing the complexity involved
in enterprise application development by using Java EE technologies directly.
• Its gives abstract layer for all the layers involved in Java EE architecture.
Why Spring: Example
ConnectionUtilizer1.java ConnectionUtilizer1.java
public class ConnectionUtilizer1 public class ConnectionUtilizer1
{ {
public static void main(String[] args) public static void main(String[] args)
{ {
System.out.print(“Utilizer is using Oracle System.out.print(“Utilizer is using MySQL
Connection”); Connection”);
} }
Observe that the Utilizer is tightly coupled with one particular Provider. This implies that we need to
modify our code every time we need a new Provider.
Due to this, it is always advisable to write different classes for Utilizer logic and Provider logic.
Why Spring: Example
OracleConeectionProvider.java MysqlConeectionProvider.java
public class OracleConnectionProvider public class MysqlConnectionProvider
{ {
public static String getOracleProvider() public static String getMysqlProvider()
{ {
return “Utilizer is using Oracle Connection”; return “Utilizer is using Mysql Connection”;
} }
} }
ConnectionUtilizer.java
public class ConnectionUtilizer
{
public static void main(String[] args)
{
OracleConnectionProvider connection=new OracleConnectionProvider(); // It we want to get
Mysql Connection we need to create its object
String name=connection.getOracleConnectionProvider(); To get connection from Oracle Provider, we call this
System.out.print(name); method of OracleConnectionProvider. For MySQL, we
} would use a different method. This involves calling two
} different methods from two different classes.
It is advisable to have a contract between Service Provider and Utilizer to avoid calling two different method
names. In Java, we can provide contract with interface.
Why Spring: Example
OracleConeectionProvider.java
ConnectionUtilizerOne.java
public class OracleConnectionProvider
public class ConnectionUtilizerOne
{
{
public static String getConnection()
public static void main(String[] args)
{
{
return “Utilizer is using Oracle
Connection contarct=new
Connection”;
OracleConnectionProvider();
}
String name=contarct.getConnection(); Connetion.java
}
System.out.print(name);
} public interface Connection
} {
public String getConnection(); MysqlConnectionProvider
ConnectionUtilizerTwo.java
public class ConnectionUtilizerTwo }
{ MysqlConeectionProvider.java
public static void main(String[] args) public class OracleConnectionProvider
{ {
Connection contarct=new public static String getConnection()
MysqlConnectionProvider(); {
String name=contarct.getConnection(); return “Utilizer is using Mysql
System.out.print(name); Connection”;
} }
} }
Why Spring: Example
To do so, it is advisable to use either properties file or XML file. We can write one container that reads the
requirement and provides required objects dynamically.
Specifying
Required
MysqlConnectionProvider
Provider Class
Myproperties.properties
MyContainer
Calling getBean() methods
Why Spring: Example
Myproperties.properties
1.provider=OracleConnectionProvider
Why Spring: Example
Let’s create a MyContainer class to fetch the properties from the Myproperties.properties file.
If you want to change the provider class, just change the properties file. It creates loose coupling
between the provider and service object.
Spring provides the container and spring configuration file (XML) to configure the required
provider classes instead of properties file. This can make the process easy.
Spring Basics
“Spring Framework is a Java platform that provides comprehensive infrastructure support for
developing Java applications. Spring handles the infrastructure to ensure focus on your application.”
Spring framework :
• It supports multiple transaction environments such as JTA, Hibernate, and JDBC (Java Database
Connectivity).
• It encourages good object-oriented design practices (e.g., interfaces, layers, separation of concerns).
• It supports annotation.
• POJOs (Plain Old Java Object) are faster than XML (Extensible Markup Language) Descriptor. Spring
supports POJO.
Advanced Java
Topic 2—Spring Architecture
Spring Architecture
Transactions
Core Container
Expression
Beans Core Context
Language
Test
Spring Architecture
DATA ACCESS/INTEGRATION LAYER
Data Access/Integration
JDBC ORM
OXM JMS
Transactions
• JDBC (Java Database Connectivity) provides a JDBC-abstraction layer that removes the need for traditional
JDBC coding.
• ORM (Object XML Mappers) provides integration layers for popular object-relational mapping APIs.
• OXM provides an abstraction layer that supports Object/XML mapping implementation.
• Spring provides Java Message Service integration to simplify the use of the JMS API.
• Spring framework provides an abstract layer on top of different underlying transaction management APIs
in transaction layer of spring.
Spring Architecture
WEB LAYER
Web (MVC/Remoting)
Web Servlet
Portlet Struts
• Web-Portlet modules: The Web-Portlet module provides the MVC implementation to be used in a
portlet environment and mirrors the functionality of Web-Servlet module.
• Web-Struts: The Web-Struts module contains the support classes for integrating a classic Struts web
tier within a Spring application.
Spring Architecture
CORE CONTAINER
Core Container
Expression
Beans Core Context
Language
• Beans: It provides BeanFactory (factory pattern). This allows you to decouple the configuration and
specification of dependencies from your actual program logic.
• Context: The Context module inherits its features from the Beans module and adds support for
internationalization (using, for example, resource bundles), event-propagation, and resource-loading.
• Expression Language modules: These provide a powerful expression language for querying and
manipulating an object graph at runtime.
Spring Architecture
MODULES
AOP (Aspect-oriented programming): It develops proxies for business layer and works as a solution for
cross cutting problem.
Test: This module supports the testing of Spring components with JUnit or TestNG.
We have discussed that Spring provides the container and provides spring configuration file (XML file) to
configure our required provider classes instead properties file.
• IOC is a design principle that explains how object creation, dependency injection, object life cycle
management, object destruction, etc., can be managed using an external entity.
• Spring Container is the external entity that implements the principles of IOC.
Spring IOC Container
It is the core container of the Spring Framework. It performs the following operations:
Java classes that are handled by this container are called spring beans.
Uses of Spring IOC Container
1. Instantiation of object
2. Dependency injection
3. Initialization to read configuration metadata
Spring Framework's IOC Container Package
• org.springframework.beans
• org.springframework.context packages
IOC Container: Working
Spring container uses POJO classes and configures metadata to produce fully configured and executable beans.
POJO
Meta Data
IOC Container
Output
Results
Types of IOC Container
There are two types of Spring Container, which are based on the following interface:
BeanFactory (I)
extends
ApplicationContext (I)
BeanFactory (interface)
implements
XMLBeanFactory (class)
Containers based on BeanFactory Interface
• Spring bean is configured in configuration file. Beanfactory container loads that bean. It is a lightweight
container.
• It is generally used in the application where data volume and speed is significant, for example, mobile
devices or applet-based applications.
Implementation for ApplicationContext
ApplicationContext
implements
• If you use FileSystemXmlApplicationContext container, you need to pass the spring configuration file to this
constructor.
• If you change the project location once, you have to change it every time.
• If you use ClassPathXmlApplicationContext, you don’t have to specify the complete path of configuration file.
• If you change project location, your file will work without modification.
• Container based on ApplicationContext provides all the features of BeanFactory. In addition to this, it
provides the following features:
o Event-Handling
o EJB integration
o Transaction
o Securities
Creating Bean Container using XmlBeanFactory Class
Creating Spring Bean Container involves creating an object of any implemented class in XmlBeanFactory.
OR
Constructor of XmlBeanFactory class takes Resource object as an argument. This represents spring
configuration file.
Resource
FileSystemResource ClassPathResource
Creating SpringBean Container
Creating Spring Bean Container involves creating an object of any implemented class.
ClassPathXmlApplicationContext .
ClassPathXmlApplicationContext .
1. Create a Java project in eclipse and add a name to it: Click New Click Project Click Java Project,
Add a name Click Next
2. Add spring jar files: Right click on project Click Buildpath Click Library Click on add external
library and add spring libraries. You can also Click on user library and add spring jar to this user-
defined library folder.
3. Create the class: Right click project Create Java class in src folder Add a name Write private
properties inside Java class Select properties and click on right Click Source Generate setter
and getter method.
class ClassName
{
//public constructor
//private variable ;
//public getter and setter methods for variable;
}
Creating Spring Applications in Eclipse
4. Create the xml file to provide the values: Right click project Create xml file Add a name Click Next.
This is called configuration file.
5. Create a test class inside src folder. Steps to write code for test class:
SpringBeanName
reference_variable=(SpringBeanName)factory.getBean("reference_id_for_class_objec
t");
• <beans
• xmlns="http://www.springframework.org/schema/beans"
• xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
• xmlns:p="http://www.springframework.org/schema/p"
• xsi:schemaLocation="http://www.springframework.org/schema/beans
• http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
• <bean id="refernce_id_for_class_object" class="ClassName">
• </bean>
• </beans>
Advanced Java
Topic 5—Dependency Injection
Dependency Injection: Example
• Setter injection: If dependency is injected to dependent object via setter method, it is known as setter
injection.
<beans…>
<bean id=” “ class=” “ >
<property name=”nameOfClassMemberVariable” value =” “ >
</property>
or
or
<beans…>
<bean id=” “ class=” “ >
<property name=”nameOfClassMemberVariable” ref =”dependency_class_id
“ > </property>
or
or
or
or
<constructor-arg>
<value> </value>
</constructor-arg>
</property>
</bean>
</beans>
Implementing Constructor Injection
IMPLEMENTATION OF CONSTRUCTOR INJECTION WHERE DEPENDENCY IS OBJECT TYPE
or
or
<constructor-arg>
<ref local/bean/parent=”providerRef”/>
</constructor-arg>
</property>
</bean>
</beans>
Injecting Collection Object
To pass multiple values to bean, we use collection injection. Spring offers four types of collection
configuration elements:
Element Description
<props> inject name-value pair where name and value are both Strings
Configuration File for Injecting Collection Injection
<beans…>
<bean id=” “ class=” “ >
<property name=”nameOfClassMemberVariable” >
<list>
<value> …... < /value>
<value>.......</value>
<value>......</value>
</list>
</property>
</bean>
</beans>
<beans…>
<bean id=” “ class=” “ >
<property name=”nameOfClassMemberVariable” >
<list>
<ref bean=” reference_id1“ />
<ref bean=” reference_id2“ />
<ref bean=” reference_id3“ />
</list>
</property>
</bean>
</beans>
Recall: Springbean factory is responsible for managing the life cycle of beans created through spring
container.
Spring container controls the life cycle of spring bean. It creates the object for bean, injects
dependencies, performs initialization operation, calls business methods, and removes it from the
container (when bean is no longer required).
SpringBean Lifecycle
InitializingBean
or
init-method Initialization ApplicationContextAware
or
@PostConstruct
DisposableBean
or Bean is removed
Bran is ready Container is destroy-method from the
to use shutdown or container
@PreDestro
SpringBean Lifecycle Components
3. BeanNameAware: An interface used to override its method setBeanName(String) and get bean name
6. Method Ready State: In this state, object is ready for use and business methods can be called.
Syntax:
@PostConstruct
InitializingBean custom init()
annotations
Initialization
custom init()
In the case of XML-based configuration metadata, you can use the init-method attribute to specify the
name of the method.
Syntax:
@PostConstruct
InitializingBean custom init()
annotations
Initialization
@PostConstruct annotations
In the case of Annotation–based configuration metadata , you can use @PostConstruct annotation of JDK at
the top of the method to specify the method as initialization method.
Syntax:
@PostConstruct
InitializingBean custom init()
annotations
Destruction
DisposibleBean
It is an interface used to implement the destroy() method. You can write initialization inside this method.
Syntax:
@PreDestroy
DisposibleBean custom destroy()
annotations
Destruction
custom destroy()
In the case of XML-based configuration metadata, you can use the destroy method attribute to specify the
name of the method.
Syntax:
@PreDestroy
DisposibleBean custom destroy()
annotations
Destruction
@PreDestroy annotations
In the case of Annotation–based configuration metadata , you can use @PreDestroy annotation of JDK at
the top of the method to specify the method as destruction method.
Syntax:
@PreDestroy
DisposibleBean custom destroy()
annotations
Advanced Java
Topic 6—Bean Wiring
What is Bean Wiring?
The Spring container can autowire relationships between collaborating beans without
using <constructor-arg> and <property> elements. This is known as Bean Wiring.
AutoWiring
1. constructor
2. byName
3. byType
4. autodetect
Types of AutoWiring
constructor
constructor Example:
When autowire=”byName” the container checks all the setter methods (that have only one parameter)
constructor within the bean.
Example:
byName
setExamDetail(ExamDetail exed);// method having parameter ExamDetail class type
byType
The container looks for beans configured with the name ExamDetail. If found, it injects all beans.
autodetect
It doesn’t bother about setter method parameter type; it only considers setter method names.
Types of AutoWiring
byType
When autowire=”byType” the container checks all the setters methods (that have one parameter) type
constructor in that bean.
Example:
byName
setExamDetail(ExamDetail exed);// method having parameter ExamDetail class type
byType
The container looks for beans configured with the name ExamDetail. If found, it injects all beans.
autodetect
It doesn’t bother about setter method name and bean id; it only considers setter method
parameter type.
Types of AutoWiring
autodetect
When autowire=”autodetect” , the Spring first tries to wire using autowire by constructor, if it does
constructor
not work, Spring tries to autowire by byType.
byName
byType
autodetect
When defining a <bean>, you have the option of declaring a scope for that bean. There can be two choices.
1) You want Spring to return the same bean instance each time one is needed
2) You want to force Spring to produce a new bean instance each time one is needed
Scope Attributes
1) singleton: Create the configured spring bean only once in the container
3) request: Create the configure spring bean once per web request. It is applicable only in web
module
4) session: Create the configured spring bean once per HttpSession. It is applicable only in web
module
5) thread: Create the configured spring ben once per each thread
Key Takeaways
Spring container controls the life cycle of spring bean. It creates the object for
bean, injects dependencies, performs initialization operation, calls business
methods, and removes it from the container (when bean is no longer required).
a. prototype
b. singleton
c. request
d. session
QUIZ
The Beans in Spring are ________ by default.
1
a. prototype
b. singleton
c. request
d. session
a. It is a lightweight framework
b. It is an opensource framework
a. It is a lightweight framework
b. It is an opensource framework