Advanced Java (Module 3)
Advanced Java (Module 3)
Advanced Java
Module 3
Page 1 of 21
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra Designed By: Prof Abhay More
400604
------------------------------------------------------------------------------
Spring Frameworks:
Introduction to Spring Framework,POJO Programming Model, Lightweight Containers(Spring
IOC container, Configuration MetaData, Configuring and using the Container) Dependency
Injection with Spring- Setter Injection, Constructor Injection, Circular Dependency,
Overriding Bean, Auto Wiring Bean Looksup, Spring Manage Beans)
------------------------------------------------------------------------------
What is Spring?
It is a lightweight, loosely coupled and integrated framework for developing enterprise applications in java. Spring
Framework is built on top of two design concepts ? Dependency Injection and Aspect Oriented Programming.
Page 2 of 21
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra Designed By: Prof Abhay More
400604
Spring Modules
The Spring Framework consists of features organized into about 20 modules. These modules are grouped
into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation, and
Test, as shown in the following diagram.
1. Core Container
The Core and Beans modules provide the fundamental parts of the framework, including the IoC and
Dependency Injection features. The BeanFactory is a sophisticated implementation of the factory pattern. It removes
the need for programmatic singletons and allows you to decouple the configuration and specification of
dependencies from your actual program logic.
The Context module builds on the solid base provided by the Core and Beans modules: it is a means to
access objects in a framework-style manner that is similar to a JNDI registry. The Context module inherits its
features from the Beans module and adds support for internationalization (using, for example, resource bundles),
event-propagation, resource-loading, and the transparent creation of contexts by, for example, a servlet container.
The Context module also supports Java EE features such as EJB, JMX ,and basic remoting. The ApplicationContext
interface is the focal point of the Context module.
The Expression Language module provides a powerful expression language for querying and manipulating
an object graph at runtime. It is an extension of the unified expression language (unified EL) as specified in the JSP
2.1 specification. The language supports setting and getting property values, property assignment, method
invocation, accessing the context of arrays, collections and indexers, logical and arithmetic operators, named
variables, and retrieval of objects by name from Spring's IoC container. It also supports list projection and selection
as well as common list aggregations.
2. Data Access/Integration
The JDBC module provides a JDBC-abstraction layer that removes the need to do tedious JDBC coding
and parsing of database-vendor specific error codes.
The ORM module provides integration layers for popular object-relational mapping APIs, including JPA,
JDO, Hibernate, and iBatis. Using the ORM package you can use all of these O/R-mapping frameworks in
combination with all of the other features Spring offers, such as the simple declarative transaction management
feature mentioned previously.
Page 3 of 21
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra Designed By: Prof Abhay More
400604
The OXM module provides an abstraction layer that supports Object/XML mapping implementations for
JAXB, Castor, XMLBeans, JiBX and XStream.
The Java Messaging Service (JMS) module contains features for producing and consuming messages.
The Transaction module supports programmatic and declarative transaction management for classes that
implement special interfaces and for all your POJOs (plain old Java objects).
3. Web
Spring's Web module provides basic web-oriented integration features such as multipart file-upload
functionality and the initialization of the IoC container using servlet listeners and a web-oriented application
context. It also contains the web-related parts of Spring's remoting support.
The Web-Servlet module contains Spring's model-view-controller (MVC) implementation for web
applications. Spring's MVC framework provides a clean separation between domain model code and web forms, and
integrates with all the other features of the Spring Framework.
The Web-Struts module contains the support classes for integrating a classic Struts web tier within a Spring
application. Note that this support is now deprecated as of Spring 3.0. Consider migrating your application to Struts
2.0 and its Spring integration or to a Spring MVC solution.
The Web-Portlet module provides the MVC implementation to be used in a portlet environment and
mirrors the functionality of Web-Servlet module.
The Instrumentation module provides class instrumentation support and classloader implementations to be
used in certain application servers.
5. Test
The Test module supports the testing of Spring components with JUnit or TestNG. It provides consistent
loading of Spring ApplicationContexts and caching of those contexts. It also provides mock objects that you can use
to test your code in isolation.
Page 4 of 21
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra Designed By: Prof Abhay More
400604
Fields can be accessed by their names. Fields are accessed only by getters and setters.
Fields can have any visiblity. Fields have only private visiblity.
Page 5 of 21
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra Designed By: Prof Abhay More
400604
Spring - IoC Containers
The Spring container is at the core of the Spring Framework. The container will
create the objects, wire them together, configure them, and manage their complete
life cycle from creation till destruction. The Spring container uses DI to manage
the components that make up an application. These objects are called Spring
Beans, which we will discuss in the next chapter.
The container gets its instructions on what objects to instantiate, configure, and
assemble by reading the configuration metadata provided. The configuration
metadata can be represented either by XML, Java annotations, or Java code. The
following diagram represents a high-level view of how Spring works. The Spring
IoC container makes use of Java POJO classes and configuration metadata to
produce a fully configured and executable system or application.
1 Spring BeanFactory Container This is the simplest container providing the basic support for DI and is defined
by the org.springframework.beans.factory.BeanFactory interface. The BeanFactory and related interfaces, such as
BeanFactoryAware, InitializingBean, DisposableBean, are still present in Spring for the purpose of backward
compatibility with a large number of third-party frameworks that integrate with Spring.
2 Spring ApplicationContext Container This container adds more enterprise-specific functionality such as the
ability to resolve textual messages from a properties file and the ability to publish application events to interested
event listeners. This container is defined by the org.springframework.context.ApplicationContext interface.
Page 6 of 21
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra Designed By: Prof Abhay More
400604
Configuration MetaData
The objects that form the backbone of your application and that are managed by the Spring IoC container are
called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container.
These beans are created with the configuration metadata that you supply to the container. Configuration MetaData
can be provided to Spring container in following ways:
XML-Based configuration: In Spring Framework, the dependencies and the services needed by beans are specified
in configuration files which are in XML format. These configuration files usually contain a lot of bean definitions
and application-specific configuration options. They generally start with a bean tag. For example:
Annotation-Based configuration: Starting from Spring 2.5 it became possible to configure the dependency
injection using annotations. So instead of using XML to describe a bean wiring, you can move the bean
configuration into the component class itself by using annotations on the relevant class, method, or field declaration.
Annotation injection is performed before XML injection. Thus, the latter configuration will override the former for
properties wired through both approaches. Annotation wiring is not turned on in the Spring container by default. So,
before we can use annotation-based wiring, we will need to enable it in our Spring configuration file. So consider
the following configuration file in case you want to use any annotation in your Spring application.
<context:annotation-config/>
<!-- bean definitions go here -->
</beans>
Once <context:annotation-config/> is configured, you can start annotating your code to indicate that Spring should
automatically wire values into properties, methods, and constructors.
Page 7 of 21
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra Designed By: Prof Abhay More
400604
Java-based configuration: The key features in Spring Framework’s new Java-configuration support are
@Configuration annotated classes and @Bean annotated methods.
@Configuration
public class StudentConfig
{
@Bean
public StudentBean myStudent()
{
return new StudentBean();
}
}
Page 8 of 21
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra Designed By: Prof Abhay More
400604
Dependency Injection with Spring
Every Java-based application has a few objects that work together to present what the end-user sees as a
working application. When writing a complex Java application, application classes should be as independent as
possible of other Java classes to increase the possibility to reuse these classes and to test them independently of other
classes while unit testing. Dependency Injection (or sometime called wiring) helps in gluing these classes together
and at the same time keeping them independent.
Consider you have an application which has a text editor component and you want to provide a spell check.
Your standard code would look something like this −
public class TextEditor {
private SpellChecker spellChecker;
public TextEditor() {
spellChecker = new SpellChecker();
}
}
What we've done here is, create a dependency between the TextEditor and the SpellChecker. In an inversion of
control scenario, we would instead do something like this −
public class TextEditor {
private SpellChecker spellChecker;
public TextEditor(SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
}
Here, the TextEditor should not worry about SpellChecker implementation. The SpellChecker will be implemented
independently and will be provided to the TextEditor at the time of TextEditor instantiation. This entire procedure is
controlled by the Spring Framework.
Here, we have removed total control from the TextEditor and kept it somewhere else (i.e. XML configuration file)
and the dependency (i.e. class SpellChecker) is being injected into the class TextEditor through a Class Constructor.
Thus the flow of control has been "inverted" by Dependency Injection (DI) because you have effectively delegated
dependances to some external system.
The second method of injecting dependency is through Setter Methods of the TextEditor class where we will create
a SpellChecker instance. This instance will be used to call setter methods to initialize TextEditor's properties.
Thus, DI exists in two major variants and the following two sub-chapters will cover both of them with examples −
Constructor-based dependency injection is accomplished when the container invokes a class constructor with a
number of arguments, each representing a dependency on the other class.
Setter-based dependency injection is accomplished by the container calling setter methods on your beans after
invoking a no-argument constructor or no-argument static factory method to instantiate your bean.
You can mix both, Constructor-based and Setter-based DI but it is a good rule of thumb to use constructor
arguments for mandatory dependencies and setters for optional dependencies.
The code is cleaner with the DI principle and decoupling is more effective when objects are provided with their
dependencies. The object does not look up its dependencies and does not know the location or class of the
dependencies, rather everything is taken care by the Spring Framework.
Page 9 of 21
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra Designed By: Prof Abhay More
400604
Example of Constructor-based Dependency Injection
TextEditor.java
package com.imcost;
public class TextEditor {
private SpellChecker spellChecker;
SpellChecker.java
package com.imcost;
public class SpellChecker {
public SpellChecker(){
System.out.println("Inside SpellChecker constructor." );
}
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
}
MainApp.java
package com.imcost;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
Page 10 of 21
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra Designed By: Prof Abhay More
400604
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
</beans>
Once you are done creating the source and bean configuration files, let us run the application. If everything is fine
with your application, it will print the following message −
Page 11 of 21
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra Designed By: Prof Abhay More
400604
Constructor arguments resolution
There may be an ambiguity while passing arguments to the constructor, in case there are more than one parameters.
To resolve this ambiguity, the order in which the constructor arguments are defined in a bean definition is the order
in which those arguments are supplied to the appropriate constructor. Consider the following class −
package x.y;
public class Foo {
public Foo(Bar bar, Baz baz) {
// ...
}
}
The following configuration works fine −
<beans>
<bean id = "foo" class = "x.y.Foo">
<constructor-arg ref = "bar"/>
<constructor-arg ref = "baz"/>
</bean>
<bean id = "bar" class = "x.y.Bar"/>
<bean id = "baz" class = "x.y.Baz"/>
</beans>
Let us check one more case where we pass different types to the constructor. Consider the following class −
package x.y;
public class Foo {
public Foo(int year, String name) {
// ...
}
}
The container can also use type matching with simple types, if you explicitly specify the type of the constructor
argument using the type attribute. For example −
<beans>
<bean id = "exampleBean" class = "examples.ExampleBean">
<constructor-arg type = "int" value = "2001"/>
<constructor-arg type = "java.lang.String" value = "Zara"/>
</bean>
</beans>
Finally, the best way to pass constructor arguments, use the index attribute to specify explicitly the index of
constructor arguments. Here, the index is 0 based. For example −
<beans>
<bean id = "exampleBean" class = "examples.ExampleBean">
<constructor-arg index = "0" value = "2001"/>
<constructor-arg index = "1" value = "Zara"/>
</bean>
</beans>
A final note, in case you are passing a reference to an object, you need to use ref attribute of <constructor-arg> tag
and if you are passing a value directly then you should use value attribute as shown above.
Page 12 of 21
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra Designed By: Prof Abhay More
400604
Example of Setter Injection
TextEditor.java
package com.imcost;
public class TextEditor {
private SpellChecker spellChecker;
SpellChecker.java
package com.imcost;
public class SpellChecker {
public SpellChecker(){
System.out.println("Inside SpellChecker constructor." );
}
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
}
MainApp.java
package com.imcost;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
Page 13 of 21
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra Designed By: Prof Abhay More
400604
Beans.XML
</beans>
You should note the difference in Beans.xml file defined in the constructor-based injection and the setter-based
injection. The only difference is inside the <bean> element where we have used <constructor-arg> tags for
constructor-based injection and <property> tags for setter-based injection.
The second important point to note is that in case you are passing a reference to an object, you need to use ref
attribute of <property> tag and if you are passing a value directly then you should use value attribute.
Once you are done creating the source and bean configuration files, let us run the application. If everything is fine
with your application, this will print the following message −
Page 14 of 21
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra Designed By: Prof Abhay More
400604
Here, you should note the difference in specifying primitive values and object references with p-namespace. The -
ref part indicates that this is not a straight value but rather a reference to another bean.
Page 15 of 21
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra Designed By: Prof Abhay More
400604
Circular Dependency in Spring
It happens when a bean A depends on another bean B, and the bean B depends on the bean A as well:
Bean A → Bean B → Bean A
Of course, we could have more beans implied:
Bean A → Bean B → Bean C → Bean D → Bean E → Bean A
When Spring context is loading all the beans, it tries to create beans in the order needed for them to work
completely. For instance, if we didn’t have a circular dependency, like the following case:
Bean A → Bean B → Bean C
Spring will create bean C, then create bean B (and inject bean C into it), then create bean A (and inject bean B into
it).But, when having a circular dependency, Spring cannot decide which of the beans should be created first, since
they depend on one another. In these cases, Spring will raise a BeanCurrentlyInCreationException while loading
context. It can happen in Spring when using constructor injection; if you use other types of injections you should not
find this problem since the dependencies will be injected when they are needed and not on the context loading.
When you have a circular dependency, it’s likely you have a design problem and the responsibilities are not well
separated. You should try to redesign the components properly so their hierarchy is well designed and there is no
need for circular dependencies.
If you cannot redesign the components (there can be many possible reasons for that: legacy code, code that has
already been tested and cannot be modified, not enough time or resources for a complete redesign…), there are some
workarounds to try.
Use Lazy
A simple way to break the cycle is saying Spring to initialize one of the beans lazily. That is: instead of fully
initializing the bean, it will create a proxy to inject it into the other bean. The injected bean will only be fully created
when it’s first needed.
Page 16 of 21
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra Designed By: Prof Abhay More
400604
Bean Overriding
Thus, bean overriding is a default behavior that happens when we define a bean within an ApplicationContext which
has the same name as another bean. It works by simply replacing the former bean in case of a name conflict.
Starting in Spring 5.1, the BeanDefinitionOverrideException was introduced to allow developers to automatically
throw the exception to prevent any unexpected bean overriding. By default, the original behavior is still available
which allows bean overriding.
Page 17 of 21
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra Designed By: Prof Abhay More
400604
Beans Auto-Wiring
The Spring container can autowire relationships between collaborating beans without using <constructor-arg> and
<property> elements, which helps cut down on the amount of XML configuration you write for a big Spring-based
application.
Following are the autowiring modes, which can be used to instruct the Spring container to use autowiring for
dependency injection. You use the autowire attribute of the <bean/> element to specify autowire mode for a bean
definition.
no:- This is default setting which means no autowiring and you should use explicit bean reference for wiring. You
have nothing to do special for this wiring. This is what you already have seen in Dependency Injection chapter.
byname:- Autowiring by property name. Spring container looks at the properties of the beans on which autowire
attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans
defined by the same names in the configuration file.
byType:- Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire
attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches
with exactly one of the beans name in configuration file. If more than one such beans exists, a fatal exception is
thrown.
constructor:- Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the
constructor argument type in the container, a fatal error is raised.
autodetect:- Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by
byType.
Auto-Wiring byName
This mode specifies autowiring by property name. Spring container looks at the beans on which auto-wire attribute
is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined
by the same names in the configuration file. If matches are found, it will inject those beans. Otherwise, bean(s) will
not be wired.
For example, if a bean definition is set to autowire byName in the configuration file, and it contains a spellChecker
property (that is, it has a setSpellChecker(...)method), Spring looks for a bean definition named spellChecker, and
uses it to set the property. Still you can wire the remaining properties using <property> tags. The following example
will illustrate the concept.
Page 18 of 21
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra Designed By: Prof Abhay More
400604
Here is the content of TextEditor.java file −
package com.imcost;
public class TextEditor {
private SpellChecker spellChecker;
private String name;
public void setSpellChecker( SpellChecker spellChecker ){
this.spellChecker = spellChecker;
}
public SpellChecker getSpellChecker() {
return spellChecker;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
}
Page 19 of 21
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra Designed By: Prof Abhay More
400604
Following is the configuration file Beans.xml in normal condition
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Definition for textEditor bean -->
<bean id = "textEditor" class = "com.imcost.TextEditor">
<property name = "spellChecker" ref = "spellChecker" />
<property name = "name" value = "Generic Text Editor" />
</bean>
But if you are going to use autowiring 'byName', then your XML configuration file will become as follows −
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Definition for textEditor bean -->
<bean id = "textEditor" class = "com.imcost.TextEditor" autowire = "byName">
<property name = "name" value = "Generic Text Editor" />
</bean>
<!-- Definition for spellChecker bean -->
<bean id = "spellChecker" class = "com.imcost.SpellChecker"></bean>
</beans>
Once you are done creating the source and bean configuration files, let us run the application. If everything is fine
with your application, it will print the following message −
Page 20 of 21
C-4, Wagle Industrial Estate,
Near Mulund Check Naka,
Thane West, opp. Aplab,
Mumbai, Maharashtra Designed By: Prof Abhay More
400604
Spring Manage Beans
A bean is the foundation of a Spring-managed application; all beans reside withing the IOC container, which is
responsible for managing their life cycle.
We can get a list of all beans within this container in two ways:
The ListableBeanFactory interface provides getBeanDefinitionNames() method which returns the names of all the
beans defined in this factory. This interface is implemented by all the bean factories that pre-loads their bean
definitions to enumerate all their bean instances.
Page 21 of 21