Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
57 views

Advanced Java (Module 3)

The document discusses Spring frameworks and modules. It introduces Spring framework as a lightweight, loosely coupled and integrated framework for developing enterprise applications in Java. It then summarizes the main Spring modules which include core container, data access/integration, web, AOP, instrumentation, and test modules. For each module, it briefly explains its purpose and key features.

Uploaded by

Sushma Sumant
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

Advanced Java (Module 3)

The document discusses Spring frameworks and modules. It introduces Spring framework as a lightweight, loosely coupled and integrated framework for developing enterprise applications in Java. It then summarizes the main Spring modules which include core container, data access/integration, web, AOP, instrumentation, and test modules. For each module, it briefly explains its purpose and key features.

Uploaded by

Sushma Sumant
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

C-4, Wagle Industrial Estate,

Near Mulund Check Naka,


Thane West, opp. Aplab,
Mumbai, Maharashtra Designed By: Prof Abhay More
400604

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)

Self learning topics: Bean Definition Profiles

------------------------------------------------------------------------------
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.

Why use Spring.(Features/Advantages)


Why to use spring is something more of a combination of desire to do things in an easy, secure and efficient way.
It's been noticed a lot of complexity of code is present in development which can be avoided, Such as code to handle
Transaction, JDBC, interaction with ORM, Exception Handling, Testing and many others. Springs provides support
for existing J2EE technologies and provide easy and efficient way to do the development.

Some of the features of spring framework are


 Lightweight and very little overhead of using framework for our development.
 Dependency Injection or Inversion of Control to write components that are independent of each other,
spring container takes care of wiring them together to achieve our work.
 Spring IoC container manages Spring Bean life cycle and project specific configurations such as JNDI
lookup.
 Spring MVC framework can be used to create web applications as well as restful web services capable of
returning XML as well as JSON response.
 Support for transaction management, JDBC operations, File uploading, Exception Handling etc with very
little configurations, either by using annotations or by spring bean configuration file.
Some of the advantages of using Spring Framework are
 Reducing direct dependencies between different components of the application, usually Spring IoC
container is responsible for initializing resources or beans and inject them as dependencies.
 Writing unit test cases are easy in Spring framework because our business logic doesn't have direct
dependencies with actual resource implementation classes. We can easily write a test configuration and
inject our mock beans for testing purposes.
 Reduces the amount of boiler-plate code, such as initializing objects, open/close resources. JdbcTemplate
helps us in removing all the boiler-plate code that comes with JDBC programming
 Spring framework is divided into several modules, it helps us in keeping our application lightweight. For
example, if we don't need Spring transaction management features, we don't need to add that dependency in
our project.
 Spring framework support most of the Java EE features and even much more. It’s always on top of the new
technologies, for example there is a Spring project for Android to help us write better code for native
android applications. This makes spring framework a complete package and we don’t need to look after
different framework for different requirement

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.

4. AOP and Instrumentation

Spring's AOP module provides an AOP Alliance-compliant aspect-oriented programming implementation


allowing you to define, for example, method-interceptors and pointcuts to cleanly decouple code that implements
functionality that should be separated. Using source-level metadata functionality, you can also incorporate
behavioral information into your code, in a manner similar to that of .NET attributes.

The separate Aspects module provides integration with AspectJ.

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

POJO Programming Model


POJO in Java stands for Plain Old Java Object. It is an ordinary object, which is not bound by any special
restriction. The POJO file does not require any special classpath. It increases the readability & re-usability of a Java
program.
POJOs are now widely accepted due to their easy maintenance. They are easy to read and write. A POJO
class does not have any naming convention for properties and methods. It is not tied to any Java Framework; any
Java Program can use it.
The term POJO was introduced by Martin Fowler ( An American software developer) in 2000. it is
available in Java from the EJB 3.0 by sun microsystem.
Generally, a POJO class contains variables and their Getters and Setters.
The POJO classes are similar to Beans as both are used to define the objects to increase the readability and
re-usability. The only difference between them that Bean Files have some restrictions but, the POJO files do not
have any special restrictions.

POJO vs Java Bean

POJO Java Bean

It doesn’t have special restrictions other than


those forced by Java language. It is a special POJO which have some restrictions.

It doesn’t provide much control on members. It provides complete control on members.

It can implement Serializable interface. It should implement serializable interface.

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.

There may/may-not be a no-arg constructor. It must have a no-arg constructor.

It is used when you don’t want to give


restriction on your members and give user It is used when you want to provide user your entity
complete access of your entity but only some part of your entity.

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.

Spring provides the following two distinct types of containers.

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.

The ApplicationContext container includes all functionality of the BeanFactorycontainer, so it is generally


recommended over BeanFactory. BeanFactory can still be used for lightweight applications like mobile devices or
applet-based applications where data volume and speed is significant.

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:

<?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">
<!-- A simple bean definition -->
<bean id = "..." class = "...">
<!-- collaborators and configuration for this bean go here -->
</bean>
</beans>

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.

<?xml version = "1.0" encoding = "UTF-8"?>


<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:context = "http://www.springframework.org/schema/context"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<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.

1. @Bean annotation plays the same role as the <bean/> element.


2.@Configuration classes allow define inter-bean dependencies by simply calling other @Bean methods in the same
class.
For example:

@Configuration
public class StudentConfig
{
@Bean
public StudentBean myStudent()
{
return new StudentBean();
}
}

Configuring and using the Container


Program as discussed in classroom using ApplicationContext

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;

public TextEditor(SpellChecker spellChecker){


System.out.println("Inside TextEditor constructor." );
this.spellChecker = spellChecker;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
}

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");

TextEditor te = (TextEditor) context.getBean("textEditor");


te.spellCheck();
}
}
Beans.XML

<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"


xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"

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">

<!-- Definition for textEditor bean -->


<bean id = "textEditor" class = "com.imcost.TextEditor">
<constructor-arg ref = "spellChecker"/>
</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 −

Inside SpellChecker constructor.


Inside TextEditor constructor.
Inside checkSpelling.

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;

// a setter method to inject the dependency.


public void setSpellChecker(SpellChecker spellChecker) {
System.out.println("Inside setSpellChecker." );
this.spellChecker = spellChecker;
}
// a getter method to return spellChecker
public SpellChecker getSpellChecker() {
return spellChecker;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
}

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");

TextEditor te = (TextEditor) context.getBean("textEditor");


te.spellCheck();
}
}

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

<?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"/>
</bean>

<!-- Definition for spellChecker bean -->


<bean id = "spellChecker" class = "com.imcost.SpellChecker"></bean>

</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 −

Inside SpellChecker constructor.


Inside setSpellChecker.
Inside checkSpelling.

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

XML Configuration using p-namespace


If you have many setter methods, then it is convenient to use p-namespace in the XML configuration file. Let us
check the difference −
Let us consider the example of a standard XML configuration file with <property> tags −
<?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">
<bean id = "john-classic" class = "com.example.Person">
<property name = "name" value = "John Doe"/>
<property name = "spouse" ref = "jane"/>
</bean>
<bean name = "jane" class = "com.example.Person">
<property name = "name" value = "John Doe"/>
</bean>
</beans>
The above XML configuration can be re-written in a cleaner way using p-namespace 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"
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 = "john-classic" class = "com.example.Person"
p:name = "John Doe"
p:spouse-ref = "jane"/>
</bean>
<bean name =" jane" class = "com.example.Person"
p:name = "John Doe"/>
</bean>
</beans>

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.

<!-- A bean definition with lazy init set on -->


<bean id = "..." class = "..." lazy-init = "true">
<!-- collaborators and configuration for this bean go here -->
</bean>

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

Spring beans are identified by their names within an ApplicationContext.

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.

Limitations with autowiring


Autowiring works best when it is used consistently across a project. If autowiring is not used in general, it might be
confusing for developers to use it to wire only one or two bean definitions. Though, autowiring can significantly
reduce the need to specify properties or constructor arguments but you should consider the limitations and
disadvantages of autowiring before using them.
Overriding possibility:- You can still specify dependencies using <constructor-arg> and <property> settings which
will always override autowiring.
Primitive data types:- You cannot autowire so-called simple properties such as primitives, Strings, and Classes.
Confusing nature:- Autowiring is less exact than explicit wiring, so if possible prefer using explict wiring.

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();
}
}

Following is the content of another dependent class file SpellChecker.java


package com.imcost;
public class SpellChecker {
public SpellChecker() {
System.out.println("Inside SpellChecker constructor." );
}
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
}

Following is the content of the MainApp.java file −


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");
TextEditor te = (TextEditor) context.getBean("textEditor");
te.spellCheck();
}
}

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>

<!-- Definition for spellChecker bean -->


<bean id = "spellChecker" class = "com.imcost.SpellChecker"></bean>
</beans>

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 −

Inside SpellChecker constructor.


Inside checkSpelling.

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:

Using a ListableBeanFactory interface


Using a Spring Boot Actuator

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.

String[] allBeanNames = applicationContext.getBeanDefinitionNames();


for(String beanName : allBeanNames) {
System.out.println(beanName);
}

Page 21 of 21

You might also like