SlideShare a Scribd company logo
What is Spring?
Spring performs two major roles for a Java application.
First Spring is a container that manages all or some of the objects used by the application. Behind the
scenes Spring configures your objects with what they need to in order to perform their roles in the
application. If you need a Data Access Object, you ask the Spring container to provide one that is
already configured with values for its data source and other properties.
Spring is also a framework because it provides libraries of classes that make it easier to accomplish
common tasks such as transaction management, database integration, email, and web applications.
What does Spring provide ?
Spring is a lightweight framework. Most of your Java classes will have nothing about Spring in their
source code. This means that you can easily transition your application from the Spring framework to
something else. It also means that transferring an existing application to use the Spring framework
doesn’t have to mean a complete code rewrite.
All Java applications that consist of multiple classes have inter-dependencies or coupling between
classes. Spring helps us develop applications that minimize the negative effects of coupling and
encourages the use of interfaces in application development. Using interfaces in our applications to
specify type helps make our applications easier to maintain and enhance later.
The Spring framework helps developers clearly separate responsibilities. Many Java applications suffer
from class bloat – that is a class that has too many responsibilities. For example a service class that
is also logging information about what its doing. Think of two situations – one is you’ve been told by
your supervisor to do your normal work but also to write down everything you do and how long it
takes you. You’d be even busier and less responsive.
A better situation would be you do your normal work, but another person observers what you’re doing
and records it and measures how long it took. Even better would be if you were totally unaware of
that other person and that other person was able to also observe and record other people’s work and
time.
What are the modules Spring Provides ?
 The Core package is the most fundamental part of the framework and provides the IoC and
Dependency Injection features. The basic concept here is the BeanFactory, which provides a
sophisticated implementation of the factory pattern which removes the need for programmatic
singletons and allows you to decouple the configuration and specification of dependencies from
your actual program logic.
 The Context package build on the solid base provided by the Core package: it provides a way
to access objects in a framework-style manner in a fashion somewhat reminiscent of a JNDI-
registry. The context package inherits its features from the beans package and adds support
for internationalization (I18N) (using for example resource bundles), event-propagation,
resource-loading, and the transparent creation of contexts by, for example, a servlet
container.
 The DAO package provides a JDBC-abstraction layer that removes the need to do tedious
JDBC coding and parsing of database-vendor specific error codes. Also, the JDBC package
provides a way to do programmatic as well as declarative transaction management, not only
for classes implementing special interfaces, but for all your POJOs (plain old Java objects).
 The ORM package provides integration layers for popular object-relational mapping APIs,
including JPA, JDO, Hibernate, and iBatis. Using the ORM package you can use all those O/R-
mappers in combination with all the other features Spring offers, such as the simple
declarative transaction management feature mentioned previously.
 Spring's AOP package provides an AOP Alliance-compliant aspect-oriented programming
implementation allowing you to define, for example, method-interceptors and pointcuts to
cleanly decouple code implementing functionality that should logically speaking be separated.
Using source-level metadata functionality you can also incorporate all kinds of behavioral
information into your code, in a manner similar to that of .NET attributes.
 Spring's Web package provides basic web-oriented integration features, such as multipart file-
upload functionality, the initialization of the IoC container using servlet listeners and a web-
oriented application context. When using Spring together with WebWork or Struts, this is the
package to integrate with.
 Spring's MVC package provides a Model-View-Controller (MVC) implementation for web-
applications. Spring's MVC framework is not just any old implementation; it provides a clean
separation between domain model code and web forms, and allows you to use all the other
features of the Spring Framework.
What are the benefits of Spring Framework?
 Not a J2EE container. Doesn’t compete with J2EE app servers. Simply provides alternatives.
 POJO-based, non-invasive framework which allows a la carte usage of its components.
 Promotes decoupling and reusability
 Reduces coding effort and enforces design discipline by providing out-of-box implicit pattern
implementations such as singleton, factory, service locator etc.
 Removes common code issues like leaking connections and more
 Support for declarative transaction management
 Easy integration with third party tools and technologies.
What is Inversion of Control ?
 Instead of objects invoking other objects, the dependant objects are added through an
external entity/container.
 Also known as the Hollywood principle – “don’t call me I will call you”
 Dependency injection
o Dependencies are “injected” by container during runtime.
o Beans define their dependencies through constructor arguments or properties
 Prevents hard-coded object creation and object/service lookup.
 Loose coupling
 Helps write effective unit tests
Explain the Spring Bean Definition ?
 The bean class is the actual implementation of the bean being described by the BeanFactory.
 Bean examples – DAO, DataSource, Transaction Manager, Persistence Managers, Service
objects, etc
 Spring config contains implementation classes while your code should program to interfaces.
 Bean behaviors include:
o Singleton or prototype
o Autowiring
o Initialization and destruction methods
 init-method
 destroy-method
 Beans can be configured to have property values set.
o Can read simple values, collections, maps, references to other beans, etc.
Explain Spring BeanFactory ?
BeanFactory is core to the Spring framework
 Lightweight container that loads bean definitions and manages your
beans.
 Configured declaratively using an XML file, or files, that determine how
beans can be referenced and wired together.
 Knows how to serve and manage a singleton or prototype defined
bean
 Responsible for lifecycle methods.
 Injects dependencies into defined beans when served
 Removes the need for ad-hoc singletons and factories
Explain the Spring ApplicationContext ?
 A Spring ApplicationContext allows you to get access to the objects
that are configured in a BeanFactory in a framework manner.
 ApplicationContext extends BeanFactory
o Adds services such as international messaging capabilities.
o Add the ability to load file resources in a generic fashion.
 Several ways to configure a context:
o XMLWebApplicationContext – Configuration for a web
application.
o ClassPathXMLApplicationContext – standalone XML
application context
o FileSystemXmlApplicationContext
 Allows you to avoid writing Service Locators
How Spring Support Struts?
 ContextLoaderPlugin
o Loads a Spring application context for the Struts ActionServlet.
o Struts Actions are managed as Spring beans.
 ActionSupport and DispatchActionSupport
o Pre-built convenience classes to provide access to the context.
o Provides methods in superclass for easy context lookup.
<plug-in
className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation"
value="/WEB-INF/applicationContext.xml"/>
</plug-in>
Explain Transaction Management in Spring ?
1. DataSourceTransactionManager - PlatformTransactionManager
implementation for single JDBC data sources. Binds a JDBC connection from
the specified data source to the thread, potentially allowing for one thread
connection per data source.
2. HibernateTransactionManager- PlatformTransactionManager
implementation for single Hibernate session factories. Binds a Hibernate
Session from the specified factory to the thread, potentially allowing for one
thread Session per factory. SessionFactoryUtils and HibernateTemplate are
aware of thread-bound Sessions and participate in such transactions
automatically. Using either is required for Hibernate access code that needs
to support this transaction handling mechanism.
3. JdoTransactionManager - PlatformTransactionManager implementation
for single JDO persistence manager factories. Binds a JDO
PersistenceManager from the specified factory to the thread, potentially
allowing for one thread PersistenceManager per factory.
PersistenceManagerFactoryUtils and JdoTemplate are aware of thread-bound
persistence managers and take part in such transactions automatically.
Using either is required for JDO access code supporting this transaction
management mechanism.
4. JtaTransactionManager - PlatformTransactionManager implementation
for JTA, i.e. J2EE container transactions. Can also work with a locally
configured JTA implementation. This transaction manager is appropriate for
handling distributed transactions, i.e. transactions that span multiple
resources, and for managing transactions on a J2EE Connector (e.g. a
persistence toolkit registered as JCA Connector).
Explian some of the DAO Support classes in Spring Framework ?
 JdbcDaoSupport
o Provides callback methods for row iteration
 HibernateDaoSupport
o Initializes Hibernate session factory
o Provides templates to invoke Hibernate API or the session
 SqlMapDaoSupport
o Provides template for iBatis SQLMaps
o Support similar to Hibernate template
What is Spring MVC?
A single shared controller instance handles a particular request type
controllers, interceptors run in the IoC container
Allows multiple DispatcherServlets that can share an “application context”
Interface based not class-based
What is bean in Spring ? How beans created and injected ?
Posted in: Spring Framework
What is a bean in Spring ?
 Typical java bean with a unique id
 Typically defined in an XML file
 In spring there are basically two types
o Singleton : One instance of the bean created and referenced
each time it is requested
o Prototype (non-singleton) : New bean created each time. Same
as new ClassName()
 Beans are normally created by Spring as late as possible
Example:
<bean id="exampleBean" class=”org.example.ExampleBean">
<property name="beanOne">
<ref bean="anotherExampleBean"/>
</property>
<property name="beanTwo">
<ref bean="yetAnotherBean"/>
</property>
<property name="integerProperty">
<value>1</value>
</property>
</bean>
How are beans created ?
 Beans are created in order based on the dependency graph
o Often they are created when the factory loads the definitions
o Can override this behavior in bean <bean class=“className”
lazy-init=“true” />
o You can also override this in the factory or context but this is not
recommended
 Spring will instantiate beans in the order required by their
dependencies
o app scope singleton - eagerly instantiated at container startup
o lazy dependency - created when dependent bean created
o VERY lazy dependency - created when accessed in code
How are beans injected ?
 A dependency graph is constructed based on the various bean
definitions
 Beans are created using constructors (mostly no-arg) or factory
methods
 Dependencies that were not injected via constructor are then injected
using setters
 Any dependency that has not been created is created as needed
When to choose Spring AOP and AspectJ AOP ?
Posted in: Spring Framework
Use Spring AOP when
 Method-only interception is sufficient
 Full power of AOP overwhelming
 Performance needs are less stringent
 Don’t want to use special compiler
 Domain object’s don’t need to be crosscutted
 Pre-written aspects meet your needs
Otherwise we use AspectJ AOP
Make sure to activate your subscription by clicking on the activation link sent to your email
What is difference between Anonymous vs ID in Spring Bean ?
Posted in: Spring Framework
Beans that do not need to be referenced elsewhere can be defined
anonymously
This bean is identified (has an id) and can be accessed to inject it into
another bean
<bean id="exampleBean" class="org.example.ExampleBean">
<property name="anotherBean" ref="someOtherBean" />
</bean>
This bean is anonymous (no id)
<bean class="org.example.ExampleBean">
<property name="anotherBean" ref="someOtherBean" />
</bean>
What are the types of Executor Interfaces ?
Posted in: Spring Framework
The java.util.concurrent package defines three Executor Interfaces :
1. Executor : a simple Interface that supports launching new tasks.
2. ExecutorService : A subinterface of Executor, which adds features that help manage the
lifecycle, both of the individual tasks and of the Executor itself.
3. ScheduledExecutorService : a subinterface of ExecutorService, supports future and/or
periodic execution of tasks.
Introduction to the Java Persistence API
Posted in: Hibernate,JPA,Spring Framework
The Java Persistence API provides Java developers with an object/relational mapping facility for
managing relational data in Java applications. Java Persistence consists of four areas:
 The Java Persistence API
 The query language
 The Java Persistence Criteria API
 Object/relational mapping metadata
The following topics are addressed here:
 Entities
 Entity Inheritance
 Managing Entities
 Querying Entities
 Further Information about Persistence
Entities
An entity is a lightweight persistence domain object. Typically, an entity represents a table in a
relational database, and each entity instance corresponds to a row in that table. The primary
programming artifact of an entity is the entity class, although entities can use helper classes.
The persistent state of an entity is represented through either persistent fields or persistent
properties. These fields or properties use object/relational mapping annotations to map the entities
and entity relationships to the relational data in the underlying data store.
Requirements for Entity Classes
An entity class must follow these requirements.
The class must be annotated with the javax.persistence.Entity annotation.
The class must have a public or protected, no-argument constructor. The class may have other
constructors.
The class must not be declared final. No methods or persistent instance variables must be declared
final.
If an entity instance is passed by value as a detached object, such as through a session bean’s remote
business interface, the class must implement the Serializable interface.
Entities may extend both entity and non-entity classes, and non-entity classes may extend entity
classes.
Persistent instance variables must be declared private, protected, or package-private and can be
accessed directly only by the entity class’s methods. Clients must access the entity’s state through
accessor or business methods.
Persistent Fields and Properties in Entity Classes
The persistent state of an entity can be accessed through either the entity’s instance variables or
properties. The fields or properties must be of the following Java language types:
Java primitive types
java.lang.String
Other serializable types, including:
Wrappers of Java primitive types
java.math.BigInteger
java.math.BigDecimal
java.util.Date
java.util.Calendar
java.sql.Date
java.sql.Time
java.sql.TimeStamp
User-defined serializable types
byte[]
Byte[]
char[]
Character[]
Enumerated types
Other entities and/or collections of entities
Embeddable classes
Entities may use persistent fields, persistent properties, or a combination of both. If the mapping
annotations are applied to the entity’s instance variables, the entity uses persistent fields. If the
mapping annotations are applied to the entity’s getter methods for JavaBeans-style properties, the
entity uses persistent properties.
Persistent Fields
If the entity class uses persistent fields, the Persistence runtime accesses entity-class instance
variables directly. All fields not annotated javax.persistence.Transient or not marked as Java transient
will be persisted to the data store. The object/relational mapping annotations must be applied to the
instance variables.
Persistent Properties
If the entity uses persistent properties, the entity must follow the method conventions of JavaBeans
components. JavaBeans-style properties use getter and setter methods that are typically named after
the entity class’s instance variable names. For every persistent property property of type Type of the
entity, there is a getter method getProperty and setter method setProperty. If the property is a
Boolean, you may use isProperty instead of getProperty. For example, if a Customer entity uses
persistent properties and has a private instance variable called firstName, the class defines a
getFirstName and setFirstName method for retrieving and setting the state of the firstName instance
variable.
The method signature for single-valued persistent properties are as follows:
Type getProperty()
void setProperty(Type type)
The object/relational mapping annotations for persistent properties must be applied to the getter
methods. Mapping annotations cannot be applied to fields or properties annotated @Transient or
marked transient.
Purpose of the ApplicationContext in Spring
Posted in: ApplicationContext In Spring,Bean Lifecycle in Spring,Bean scopes in Spring,Spring Framework,Spring IoC
While the beans package provides basic functionality for managing and manipulating beans, often in a
programmatic way, the context package adds ApplicationContext, which enhances BeanFactory
functionality in a more framework-oriented style.
A bean factory is fine for simple applications, but to take advantage of the full power of the Spring
Framework, you’ll probably want to load your application beans using Spring’s more advanced
container, the application context.
Many users will use ApplicationContext in a completely declarative fashion, not even having to create
it manually, but instead relying on support classes such as ContextLoader to automatically start an
ApplicationContext as part of the normal startup process of a J2EE web-app. Of course, it is still
possible to programmatically create an ApplicationContext.
The basis for the context package is the ApplicationContext interface, located in the
org.springframework.context package. Deriving from the BeanFactory interface, it provides all the
functionality of BeanFactory.
You could also implement your own ApplicationContext and add support for loading from other
resources (such as a database). While many Contexts are available for loading beans, you’ll only need
a few, which are listed below. The others are internal classes that are used by the framework itself.
1 ) ClassPathXmlApplicationContext: Loads context files from the classpath (that is, WEB-
INF/classes or WEB-INF/lib for JARs) in a web application. Initializes using a
new ClassPathXmlApplicationContext(path)
where path is the path to the file.
2 ) FileSystemXmlApplicationContext: Loads context files from the file system, which is nice for
testing. Initializes using a
new FileSystemXmlApplicationContext (path)
where path is a relative or absolute path to the file. The path argument can also be a String array of
paths.
3. XmlWebApplicationContext: Loads context files internally by the ContextLoaderListener, but can
be used outside of it. For instance, if you are running a container that doesn’t load Listeners in the
order specified in web.xml, you may have to use this in another Listener. Below is the code to use this
Loader.
?
1
2
3
4
XmlWebApplicationContext context =
new XmlWebApplicationContext();
context.setServletContext(ctx);
context.refresh();
Once you’ve obtained a reference to a context, you can get references to beans using
ctx.getBean(“beanId”)
You will need to cast it to a specific type, but that’s the easy part. Of the above contexts,
ClassPathXmlApplicationContext is the most flexible. It doesn’t care where the files are, as long as
they’re in the classpath. This allows you to move files around and simply change the classpath.

Aspect-Oriented Programming(AOP) in Spring - Part 1
Posted in: AOP,Spring Framework,Spring IoC
Aspect-Oriented Programming (AOP) Introduction :
AOP is a new methodology that provides separation of crosscutting concerns by introducing a new unit
of modularization—an aspect—that crosscuts other modules. With AOP you implement crosscutting
concerns in aspects instead of fusing them in the core modules. An aspect weaver, which is a
compiler-like entity, composes the final system by combining the core and crosscutting modules
through a process called weaving.
Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing
another way of thinking about program structure. The key unit of modularity in OOP is the class,
whereas in AOP the unit of modularity is the aspect.
AOP Fundamentals:
 Aspect-oriented programming (AOP) provides for simplified application of cross-cutting
concerns.
o Transaction management
o Security
o Logging
o Auditing
o Locking
 AOP sometimes (partially) achieved via Decorators or Proxies
o CORBA Portable Interceptors
o Servlet Filters
 Aspect : Implementation of a cross-cutting concern.
 Spring Advisors or Interceptors
 Joinpoint : Execution point to target
o Typically, methods
 Advice : Action taken at a particular joinpoint.
 Pointcut : A set of joinpoints specifying where advice should be applied (e.g. Regular
expression)
 Introduction/Mixin - Adding methods or fields to an advised class.
 Weaving : Assembling aspects into advised objects.

Installing Spring IDE Plugin in Eclipse using update site
Posted in: Plugins,Spring Framework
Prerequisites
Before starting ensure that you have the following installed:
 Eclipse 3.3 with WTP - http://www.eclipse.org/downloads/moreinfo/jee.php
 Spring Framework - http://www.springframework.org/download
For completeness, it's best if you install the version with depedencies
If you know how to install eclipse plugin, use the Eclipse Software Update wizard to go to the
SpringIDE update site to download the latest version (http://springide.org/updatesite). Otherwise you
can follow the tutorial.
Spring IDE
Spring IDE is an eclipse plug-in that helps in developing Spring Application. First we will see how to
install the Spring IDE and later we will create our first Spring project using it.
To install Spring IDE, Go to Help -> Software Updates.
Click the "Add Site" button and enter "http://springide.org/updatesite" in the Add Site popup.
Select all the Spring IDE features and click Install.
Java bean calls :
?
1
2
3
4
5
6
7
8
9
10
11
12
13
package com.javastuff.spring;
public class SpringExample {
public String message;
/**
* @return the message
*/
public String getMessage() {
return message;
}
/**
* @param message
* the message to set
*/
14
15
16
17
18
19
20
public void setMessage(String message) {
this.message = message;
}
}
ApplicationContext.xml
?
1
2
3
4
5
6
7
8
9
10
11
<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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="springExample" class="com.javastuff.spring.SpringExample">
<property name="message" value="Hello Friend, Welcome To Javastuff !!!! "/>
</bean>
</beans>
TestClass.Java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.javastuff.Test;
import org.springframework.beans.factory.BeanFactory;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
import com.javastuff.spring.SpringExample;
public class TestClass {
public static void main(String[] args) {
BeanFactory factory = new ClassPathXmlApplicationContext(
"ApplicationContext.xml");
SpringExample se = (SpringExample)
factory.getBean("springExample");
System.out.println(" Message : " + se.getMessage());
}
}
OutPut:
Message : Hello Friend, Welcome To Javastuff !!!!

More Related Content

DOCX
Spring notes
PPTX
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
PDF
Spring Framework -I
DOCX
Hibernate notes
PDF
Hibernate Interview Questions
PDF
Spring Framework - III
PPTX
Multithreading in java
PDF
Introduction to Spring's Dependency Injection
Spring notes
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Spring Framework -I
Hibernate notes
Hibernate Interview Questions
Spring Framework - III
Multithreading in java
Introduction to Spring's Dependency Injection

What's hot (20)

PPTX
Introduction to Ibatis by Rohit
ODP
Spring User Guide
PPTX
Spring & hibernate
PPTX
Spring Framework Rohit
PDF
Hibernate complete notes_by_sekhar_sir_javabynatara_j
PPTX
Spring framework
DOC
Hibernate tutorial for beginners
PPTX
Spring framework
ODP
Spring survey
PDF
Hibernate I
PDF
Spring core module
PPT
Spring hibernate tutorial
PPS
Java Hibernate Programming with Architecture Diagram and Example
PPTX
Spring jdbc dao
PDF
Spring Framework-II
PPTX
Spring Framework
PDF
Hibernate Interview Questions | Edureka
PPT
Spring Framework
PDF
Overview of JEE Technology
DOCX
TY.BSc.IT Java QB U6
Introduction to Ibatis by Rohit
Spring User Guide
Spring & hibernate
Spring Framework Rohit
Hibernate complete notes_by_sekhar_sir_javabynatara_j
Spring framework
Hibernate tutorial for beginners
Spring framework
Spring survey
Hibernate I
Spring core module
Spring hibernate tutorial
Java Hibernate Programming with Architecture Diagram and Example
Spring jdbc dao
Spring Framework-II
Spring Framework
Hibernate Interview Questions | Edureka
Spring Framework
Overview of JEE Technology
TY.BSc.IT Java QB U6
Ad

Similar to Spring 2 (20)

PPTX
Spring framework-tutorial
PPTX
Spring (1)
PPT
Spring ppt
PDF
Spring Framework Tutorial | VirtualNuggets
PPTX
1. Spring intro IoC
 
PPTX
Spring framework Introduction
PPT
Hybernat and structs, spring classes in mumbai
PDF
Spring framework Introduction
PPTX
Introduction to Spring Framework
PPTX
Introduction to Spring Framework
 
PPT
Spring introduction
PPT
Spring - a framework written by developers
DOCX
Spring Fa Qs
PPTX
unit_1_spring_1.pptxfgfgggjffgggddddgggg
PDF
Introduction to Spring Framework
PPT
Spring Framework
PPTX
Spring framework
PPT
PPTX
Introduction to Spring Framework
PPTX
Spring Basics
Spring framework-tutorial
Spring (1)
Spring ppt
Spring Framework Tutorial | VirtualNuggets
1. Spring intro IoC
 
Spring framework Introduction
Hybernat and structs, spring classes in mumbai
Spring framework Introduction
Introduction to Spring Framework
Introduction to Spring Framework
 
Spring introduction
Spring - a framework written by developers
Spring Fa Qs
unit_1_spring_1.pptxfgfgggjffgggddddgggg
Introduction to Spring Framework
Spring Framework
Spring framework
Introduction to Spring Framework
Spring Basics
Ad

Recently uploaded (20)

PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Empathic Computing: Creating Shared Understanding
PDF
Approach and Philosophy of On baking technology
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Encapsulation theory and applications.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Modernizing your data center with Dell and AMD
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Empathic Computing: Creating Shared Understanding
Approach and Philosophy of On baking technology
20250228 LYD VKU AI Blended-Learning.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Encapsulation theory and applications.pdf
Encapsulation_ Review paper, used for researhc scholars
The Rise and Fall of 3GPP – Time for a Sabbatical?
The AUB Centre for AI in Media Proposal.docx
Diabetes mellitus diagnosis method based random forest with bat algorithm
NewMind AI Monthly Chronicles - July 2025
Building Integrated photovoltaic BIPV_UPV.pdf
Modernizing your data center with Dell and AMD
Spectral efficient network and resource selection model in 5G networks
Bridging biosciences and deep learning for revolutionary discoveries: a compr...

Spring 2

  • 1. What is Spring? Spring performs two major roles for a Java application. First Spring is a container that manages all or some of the objects used by the application. Behind the scenes Spring configures your objects with what they need to in order to perform their roles in the application. If you need a Data Access Object, you ask the Spring container to provide one that is already configured with values for its data source and other properties. Spring is also a framework because it provides libraries of classes that make it easier to accomplish common tasks such as transaction management, database integration, email, and web applications. What does Spring provide ? Spring is a lightweight framework. Most of your Java classes will have nothing about Spring in their source code. This means that you can easily transition your application from the Spring framework to something else. It also means that transferring an existing application to use the Spring framework doesn’t have to mean a complete code rewrite. All Java applications that consist of multiple classes have inter-dependencies or coupling between classes. Spring helps us develop applications that minimize the negative effects of coupling and encourages the use of interfaces in application development. Using interfaces in our applications to specify type helps make our applications easier to maintain and enhance later. The Spring framework helps developers clearly separate responsibilities. Many Java applications suffer from class bloat – that is a class that has too many responsibilities. For example a service class that is also logging information about what its doing. Think of two situations – one is you’ve been told by your supervisor to do your normal work but also to write down everything you do and how long it takes you. You’d be even busier and less responsive. A better situation would be you do your normal work, but another person observers what you’re doing and records it and measures how long it took. Even better would be if you were totally unaware of that other person and that other person was able to also observe and record other people’s work and time. What are the modules Spring Provides ?  The Core package is the most fundamental part of the framework and provides the IoC and Dependency Injection features. The basic concept here is the BeanFactory, which provides a sophisticated implementation of the factory pattern which removes the need for programmatic singletons and allows you to decouple the configuration and specification of dependencies from your actual program logic.  The Context package build on the solid base provided by the Core package: it provides a way to access objects in a framework-style manner in a fashion somewhat reminiscent of a JNDI- registry. The context package inherits its features from the beans package and adds support for internationalization (I18N) (using for example resource bundles), event-propagation, resource-loading, and the transparent creation of contexts by, for example, a servlet container.  The DAO package provides a JDBC-abstraction layer that removes the need to do tedious JDBC coding and parsing of database-vendor specific error codes. Also, the JDBC package provides a way to do programmatic as well as declarative transaction management, not only for classes implementing special interfaces, but for all your POJOs (plain old Java objects).  The ORM package provides integration layers for popular object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis. Using the ORM package you can use all those O/R- mappers in combination with all the other features Spring offers, such as the simple declarative transaction management feature mentioned previously.
  • 2.  Spring's AOP package provides an AOP Alliance-compliant aspect-oriented programming implementation allowing you to define, for example, method-interceptors and pointcuts to cleanly decouple code implementing functionality that should logically speaking be separated. Using source-level metadata functionality you can also incorporate all kinds of behavioral information into your code, in a manner similar to that of .NET attributes.  Spring's Web package provides basic web-oriented integration features, such as multipart file- upload functionality, the initialization of the IoC container using servlet listeners and a web- oriented application context. When using Spring together with WebWork or Struts, this is the package to integrate with.  Spring's MVC package provides a Model-View-Controller (MVC) implementation for web- applications. Spring's MVC framework is not just any old implementation; it provides a clean separation between domain model code and web forms, and allows you to use all the other features of the Spring Framework. What are the benefits of Spring Framework?  Not a J2EE container. Doesn’t compete with J2EE app servers. Simply provides alternatives.  POJO-based, non-invasive framework which allows a la carte usage of its components.  Promotes decoupling and reusability  Reduces coding effort and enforces design discipline by providing out-of-box implicit pattern implementations such as singleton, factory, service locator etc.  Removes common code issues like leaking connections and more  Support for declarative transaction management  Easy integration with third party tools and technologies. What is Inversion of Control ?  Instead of objects invoking other objects, the dependant objects are added through an external entity/container.  Also known as the Hollywood principle – “don’t call me I will call you”  Dependency injection o Dependencies are “injected” by container during runtime. o Beans define their dependencies through constructor arguments or properties  Prevents hard-coded object creation and object/service lookup.  Loose coupling  Helps write effective unit tests Explain the Spring Bean Definition ?  The bean class is the actual implementation of the bean being described by the BeanFactory.  Bean examples – DAO, DataSource, Transaction Manager, Persistence Managers, Service objects, etc  Spring config contains implementation classes while your code should program to interfaces.  Bean behaviors include: o Singleton or prototype o Autowiring o Initialization and destruction methods  init-method  destroy-method  Beans can be configured to have property values set. o Can read simple values, collections, maps, references to other beans, etc. Explain Spring BeanFactory ?
  • 3. BeanFactory is core to the Spring framework  Lightweight container that loads bean definitions and manages your beans.  Configured declaratively using an XML file, or files, that determine how beans can be referenced and wired together.  Knows how to serve and manage a singleton or prototype defined bean  Responsible for lifecycle methods.  Injects dependencies into defined beans when served  Removes the need for ad-hoc singletons and factories Explain the Spring ApplicationContext ?  A Spring ApplicationContext allows you to get access to the objects that are configured in a BeanFactory in a framework manner.  ApplicationContext extends BeanFactory o Adds services such as international messaging capabilities. o Add the ability to load file resources in a generic fashion.  Several ways to configure a context: o XMLWebApplicationContext – Configuration for a web application. o ClassPathXMLApplicationContext – standalone XML application context o FileSystemXmlApplicationContext  Allows you to avoid writing Service Locators How Spring Support Struts?  ContextLoaderPlugin o Loads a Spring application context for the Struts ActionServlet. o Struts Actions are managed as Spring beans.  ActionSupport and DispatchActionSupport o Pre-built convenience classes to provide access to the context. o Provides methods in superclass for easy context lookup. <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"> <set-property property="contextConfigLocation" value="/WEB-INF/applicationContext.xml"/> </plug-in>
  • 4. Explain Transaction Management in Spring ? 1. DataSourceTransactionManager - PlatformTransactionManager implementation for single JDBC data sources. Binds a JDBC connection from the specified data source to the thread, potentially allowing for one thread connection per data source. 2. HibernateTransactionManager- PlatformTransactionManager implementation for single Hibernate session factories. Binds a Hibernate Session from the specified factory to the thread, potentially allowing for one thread Session per factory. SessionFactoryUtils and HibernateTemplate are aware of thread-bound Sessions and participate in such transactions automatically. Using either is required for Hibernate access code that needs to support this transaction handling mechanism. 3. JdoTransactionManager - PlatformTransactionManager implementation for single JDO persistence manager factories. Binds a JDO PersistenceManager from the specified factory to the thread, potentially allowing for one thread PersistenceManager per factory. PersistenceManagerFactoryUtils and JdoTemplate are aware of thread-bound persistence managers and take part in such transactions automatically. Using either is required for JDO access code supporting this transaction management mechanism. 4. JtaTransactionManager - PlatformTransactionManager implementation for JTA, i.e. J2EE container transactions. Can also work with a locally configured JTA implementation. This transaction manager is appropriate for handling distributed transactions, i.e. transactions that span multiple resources, and for managing transactions on a J2EE Connector (e.g. a persistence toolkit registered as JCA Connector). Explian some of the DAO Support classes in Spring Framework ?  JdbcDaoSupport o Provides callback methods for row iteration  HibernateDaoSupport o Initializes Hibernate session factory o Provides templates to invoke Hibernate API or the session  SqlMapDaoSupport o Provides template for iBatis SQLMaps o Support similar to Hibernate template What is Spring MVC?
  • 5. A single shared controller instance handles a particular request type controllers, interceptors run in the IoC container Allows multiple DispatcherServlets that can share an “application context” Interface based not class-based What is bean in Spring ? How beans created and injected ? Posted in: Spring Framework What is a bean in Spring ?  Typical java bean with a unique id  Typically defined in an XML file  In spring there are basically two types o Singleton : One instance of the bean created and referenced each time it is requested o Prototype (non-singleton) : New bean created each time. Same as new ClassName()  Beans are normally created by Spring as late as possible Example: <bean id="exampleBean" class=”org.example.ExampleBean"> <property name="beanOne"> <ref bean="anotherExampleBean"/> </property> <property name="beanTwo"> <ref bean="yetAnotherBean"/> </property> <property name="integerProperty"> <value>1</value> </property> </bean> How are beans created ?  Beans are created in order based on the dependency graph o Often they are created when the factory loads the definitions o Can override this behavior in bean <bean class=“className” lazy-init=“true” /> o You can also override this in the factory or context but this is not recommended  Spring will instantiate beans in the order required by their dependencies
  • 6. o app scope singleton - eagerly instantiated at container startup o lazy dependency - created when dependent bean created o VERY lazy dependency - created when accessed in code How are beans injected ?  A dependency graph is constructed based on the various bean definitions  Beans are created using constructors (mostly no-arg) or factory methods  Dependencies that were not injected via constructor are then injected using setters  Any dependency that has not been created is created as needed When to choose Spring AOP and AspectJ AOP ? Posted in: Spring Framework Use Spring AOP when  Method-only interception is sufficient  Full power of AOP overwhelming  Performance needs are less stringent  Don’t want to use special compiler  Domain object’s don’t need to be crosscutted  Pre-written aspects meet your needs Otherwise we use AspectJ AOP Make sure to activate your subscription by clicking on the activation link sent to your email What is difference between Anonymous vs ID in Spring Bean ? Posted in: Spring Framework Beans that do not need to be referenced elsewhere can be defined anonymously This bean is identified (has an id) and can be accessed to inject it into another bean <bean id="exampleBean" class="org.example.ExampleBean"> <property name="anotherBean" ref="someOtherBean" /> </bean> This bean is anonymous (no id)
  • 7. <bean class="org.example.ExampleBean"> <property name="anotherBean" ref="someOtherBean" /> </bean> What are the types of Executor Interfaces ? Posted in: Spring Framework The java.util.concurrent package defines three Executor Interfaces : 1. Executor : a simple Interface that supports launching new tasks. 2. ExecutorService : A subinterface of Executor, which adds features that help manage the lifecycle, both of the individual tasks and of the Executor itself. 3. ScheduledExecutorService : a subinterface of ExecutorService, supports future and/or periodic execution of tasks. Introduction to the Java Persistence API Posted in: Hibernate,JPA,Spring Framework The Java Persistence API provides Java developers with an object/relational mapping facility for managing relational data in Java applications. Java Persistence consists of four areas:  The Java Persistence API  The query language  The Java Persistence Criteria API  Object/relational mapping metadata The following topics are addressed here:  Entities  Entity Inheritance  Managing Entities  Querying Entities  Further Information about Persistence Entities An entity is a lightweight persistence domain object. Typically, an entity represents a table in a relational database, and each entity instance corresponds to a row in that table. The primary programming artifact of an entity is the entity class, although entities can use helper classes. The persistent state of an entity is represented through either persistent fields or persistent properties. These fields or properties use object/relational mapping annotations to map the entities and entity relationships to the relational data in the underlying data store. Requirements for Entity Classes An entity class must follow these requirements. The class must be annotated with the javax.persistence.Entity annotation. The class must have a public or protected, no-argument constructor. The class may have other constructors.
  • 8. The class must not be declared final. No methods or persistent instance variables must be declared final. If an entity instance is passed by value as a detached object, such as through a session bean’s remote business interface, the class must implement the Serializable interface. Entities may extend both entity and non-entity classes, and non-entity classes may extend entity classes. Persistent instance variables must be declared private, protected, or package-private and can be accessed directly only by the entity class’s methods. Clients must access the entity’s state through accessor or business methods. Persistent Fields and Properties in Entity Classes The persistent state of an entity can be accessed through either the entity’s instance variables or properties. The fields or properties must be of the following Java language types: Java primitive types java.lang.String Other serializable types, including: Wrappers of Java primitive types java.math.BigInteger java.math.BigDecimal java.util.Date java.util.Calendar java.sql.Date java.sql.Time java.sql.TimeStamp User-defined serializable types byte[] Byte[] char[] Character[] Enumerated types Other entities and/or collections of entities Embeddable classes Entities may use persistent fields, persistent properties, or a combination of both. If the mapping annotations are applied to the entity’s instance variables, the entity uses persistent fields. If the mapping annotations are applied to the entity’s getter methods for JavaBeans-style properties, the entity uses persistent properties.
  • 9. Persistent Fields If the entity class uses persistent fields, the Persistence runtime accesses entity-class instance variables directly. All fields not annotated javax.persistence.Transient or not marked as Java transient will be persisted to the data store. The object/relational mapping annotations must be applied to the instance variables. Persistent Properties If the entity uses persistent properties, the entity must follow the method conventions of JavaBeans components. JavaBeans-style properties use getter and setter methods that are typically named after the entity class’s instance variable names. For every persistent property property of type Type of the entity, there is a getter method getProperty and setter method setProperty. If the property is a Boolean, you may use isProperty instead of getProperty. For example, if a Customer entity uses persistent properties and has a private instance variable called firstName, the class defines a getFirstName and setFirstName method for retrieving and setting the state of the firstName instance variable. The method signature for single-valued persistent properties are as follows: Type getProperty() void setProperty(Type type) The object/relational mapping annotations for persistent properties must be applied to the getter methods. Mapping annotations cannot be applied to fields or properties annotated @Transient or marked transient. Purpose of the ApplicationContext in Spring Posted in: ApplicationContext In Spring,Bean Lifecycle in Spring,Bean scopes in Spring,Spring Framework,Spring IoC While the beans package provides basic functionality for managing and manipulating beans, often in a programmatic way, the context package adds ApplicationContext, which enhances BeanFactory functionality in a more framework-oriented style. A bean factory is fine for simple applications, but to take advantage of the full power of the Spring Framework, you’ll probably want to load your application beans using Spring’s more advanced container, the application context. Many users will use ApplicationContext in a completely declarative fashion, not even having to create it manually, but instead relying on support classes such as ContextLoader to automatically start an ApplicationContext as part of the normal startup process of a J2EE web-app. Of course, it is still possible to programmatically create an ApplicationContext. The basis for the context package is the ApplicationContext interface, located in the org.springframework.context package. Deriving from the BeanFactory interface, it provides all the functionality of BeanFactory. You could also implement your own ApplicationContext and add support for loading from other resources (such as a database). While many Contexts are available for loading beans, you’ll only need a few, which are listed below. The others are internal classes that are used by the framework itself. 1 ) ClassPathXmlApplicationContext: Loads context files from the classpath (that is, WEB- INF/classes or WEB-INF/lib for JARs) in a web application. Initializes using a new ClassPathXmlApplicationContext(path) where path is the path to the file. 2 ) FileSystemXmlApplicationContext: Loads context files from the file system, which is nice for testing. Initializes using a
  • 10. new FileSystemXmlApplicationContext (path) where path is a relative or absolute path to the file. The path argument can also be a String array of paths. 3. XmlWebApplicationContext: Loads context files internally by the ContextLoaderListener, but can be used outside of it. For instance, if you are running a container that doesn’t load Listeners in the order specified in web.xml, you may have to use this in another Listener. Below is the code to use this Loader. ? 1 2 3 4 XmlWebApplicationContext context = new XmlWebApplicationContext(); context.setServletContext(ctx); context.refresh(); Once you’ve obtained a reference to a context, you can get references to beans using ctx.getBean(“beanId”) You will need to cast it to a specific type, but that’s the easy part. Of the above contexts, ClassPathXmlApplicationContext is the most flexible. It doesn’t care where the files are, as long as they’re in the classpath. This allows you to move files around and simply change the classpath.  Aspect-Oriented Programming(AOP) in Spring - Part 1 Posted in: AOP,Spring Framework,Spring IoC Aspect-Oriented Programming (AOP) Introduction : AOP is a new methodology that provides separation of crosscutting concerns by introducing a new unit of modularization—an aspect—that crosscuts other modules. With AOP you implement crosscutting concerns in aspects instead of fusing them in the core modules. An aspect weaver, which is a compiler-like entity, composes the final system by combining the core and crosscutting modules through a process called weaving. Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. AOP Fundamentals:  Aspect-oriented programming (AOP) provides for simplified application of cross-cutting concerns. o Transaction management o Security
  • 11. o Logging o Auditing o Locking  AOP sometimes (partially) achieved via Decorators or Proxies o CORBA Portable Interceptors o Servlet Filters  Aspect : Implementation of a cross-cutting concern.  Spring Advisors or Interceptors  Joinpoint : Execution point to target o Typically, methods  Advice : Action taken at a particular joinpoint.  Pointcut : A set of joinpoints specifying where advice should be applied (e.g. Regular expression)  Introduction/Mixin - Adding methods or fields to an advised class.  Weaving : Assembling aspects into advised objects.  Installing Spring IDE Plugin in Eclipse using update site Posted in: Plugins,Spring Framework Prerequisites Before starting ensure that you have the following installed:  Eclipse 3.3 with WTP - http://www.eclipse.org/downloads/moreinfo/jee.php  Spring Framework - http://www.springframework.org/download For completeness, it's best if you install the version with depedencies If you know how to install eclipse plugin, use the Eclipse Software Update wizard to go to the SpringIDE update site to download the latest version (http://springide.org/updatesite). Otherwise you can follow the tutorial. Spring IDE Spring IDE is an eclipse plug-in that helps in developing Spring Application. First we will see how to install the Spring IDE and later we will create our first Spring project using it. To install Spring IDE, Go to Help -> Software Updates. Click the "Add Site" button and enter "http://springide.org/updatesite" in the Add Site popup.
  • 12. Select all the Spring IDE features and click Install. Java bean calls : ? 1 2 3 4 5 6 7 8 9 10 11 12 13 package com.javastuff.spring; public class SpringExample { public String message; /** * @return the message */ public String getMessage() { return message; } /** * @param message * the message to set */
  • 13. 14 15 16 17 18 19 20 public void setMessage(String message) { this.message = message; } } ApplicationContext.xml ? 1 2 3 4 5 6 7 8 9 10 11 <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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean id="springExample" class="com.javastuff.spring.SpringExample"> <property name="message" value="Hello Friend, Welcome To Javastuff !!!! "/> </bean> </beans> TestClass.Java ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 package com.javastuff.Test; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.javastuff.spring.SpringExample; public class TestClass { public static void main(String[] args) { BeanFactory factory = new ClassPathXmlApplicationContext( "ApplicationContext.xml"); SpringExample se = (SpringExample) factory.getBean("springExample"); System.out.println(" Message : " + se.getMessage()); } } OutPut: Message : Hello Friend, Welcome To Javastuff !!!!