+ All Categories
Home > Documents > Spring Notes - TechnicalStack

Spring Notes - TechnicalStack

Date post: 11-Jun-2022
Category:
Upload: others
View: 5 times
Download: 0 times
Share this document with a friend
211
This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT Spring Notes Contents What is Spring?. 5 Why use Spring.(Features/Advantages). 5 Some of the features of spring framework are: 5 Some of the advantages of using Spring Framework are: 5 When to use Spring. 6 What Are Spring Modules/Different modules of the spring frame work?. 6 Name some of the design patterns used in Spring Framework?. 7 What is IOC and Dependency Injection?. 7 What is Dependency Injection?. 8 Differentiating with dependency injection. 8 Implementing inversion of control design pattern. 8 o Constructor Injection. 8 o Setter Injection. 8 o Interface Injection. 8 Spring Hello World, Setter Injection With Primitive Values. 8 Setter Injection With Objects, Spring Dependency In The Form Of Objects. 12 Spring Setter Injection, Dependency In The Form Of Collections. 19 Spring Dependency Injection With Set Collection Property. 19 Complete Example On Spring Setter Injection With Set Collection Property. 21 Spring Dependency Injection with List Collection Property. 23 Spring Dependency Injection With Map Collection Property. 26 Constructor Injection In Spring [ Full Concept . 29 Dependency in the form of object in this constructor injection. 31 Difference between Setter Injection and Constructor Injection. 34 Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 1/211 |
Transcript
Page 1: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Spring Notes

Contents

What is Spring?. 5

Why use Spring.(Features/Advantages). 5

Some of the features of spring framework are: 5

Some of the advantages of using Spring Framework are: 5

When to use Spring. 6

What Are Spring Modules/Different modules of the spring frame work?. 6

Name some of the design patterns used in Spring Framework?. 7

What is IOC and Dependency Injection?. 7

What is Dependency Injection?. 8

Differentiating with dependency injection. 8

Implementing inversion of control design pattern. 8

o       Constructor Injection. 8

o       Setter Injection. 8

o       Interface Injection. 8

Spring Hello World, Setter Injection With Primitive Values. 8

Setter Injection With Objects, Spring Dependency In The Form Of Objects. 12

Spring Setter Injection, Dependency In The Form Of Collections. 19

Spring Dependency Injection With Set Collection Property. 19

Complete Example On Spring Setter Injection With Set Collection Property. 21

Spring Dependency Injection with List Collection Property. 23

Spring Dependency Injection With Map Collection Property. 26

Constructor Injection In Spring [ Full Concept . 29

Dependency in the form of object in this constructor injection. 31

Difference between Setter Injection and Constructor Injection. 34

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 1/211 |

Page 2: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

How to inject a java.util.Properties into a Spring Bean?. 35

IoC containers: 35

There are two types of IoC containers: 36

Implementation of BeanFactory. 36

Implementations of ApplicationContext. 36

FileSystemXmlApplicationContext: 36]

ClassPathXmlApplicationContext. 36]

WebXmlApplicationContext: 37]

What is the difference between Bean Factory and Application Context ?. 37

What are Spring beans?. 37

What does a bean definition contain?. 37

How do you provide configuration metadata to the Spring Container?. 37

How do you define a bean scope?. 38

Ways to instantiate beans in spring. 38

Instantiation using a constructor. 38]

Instantiation using a static factory method. 38]

Instantiation using an instance factory method. 38]

Setter injection. 39]

Constructor injection. 39]

What is difference between component and service?. 39

How DI is different from Service locator pattern?. 40

Which one should be better to use i.e. service locator or dependency injection?. 40

Which is better constructor injection or setter injection?. 40

What bean scopes does Spring support? Explain them. 40

What are different ways to configure a class as Spring Bean?. 41

What are different scopes of Spring Bean?. 41

What is Spring Java-Based Configuration?. 42

What is Spring Annotation-based Configuration?. 44

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 2/211 |

Page 3: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

What is Spring Bean life cycle?. 44

How to get ServletContext and ServletConfig object in a Spring Bean?. 45

Spring Bean Life Cycle Methods ? InitializingBean, DisposableBean, @PostConstruct, @PreDestroy and *Aware interfaces  45

@PostConstruct and @PreDestroy Annotations. 46

@PostConstruct and @PreDestroy Example. 49

Spring Aware Interfaces. 51

Explain Bean lifecycle in Spring framework?. 54

What are inner beans in Spring?. 55

How can you inject Java Collection in Spring?. 55

What is Bean wiring and @Autowired annotation?. 55

What is bean auto wiring?. 55

What are different Modes of auto wiring?. 55

no: 56]

byName: 56]

byType. 56]

constructor. 56]

autodetect: 56]

What are the limitations with autowiring?. 56

Example On Spring Autowiring byName. 56

Example On Spring Autowiring byType. 59

Example On Spring Autowiring by Constructor. 62

Example On Spring Autowiring by Autodetect. 64

What is Annotation-based container configuration?. 66

How do you turn on annotation wiring?. 66

What does @Required annotation mean?. 66

Spring @Required Annotation and RequiredAnnotationBeanPostProcessor Example. 67

How to use @Required annotation. 67

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 3/211 |

Page 4: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

RequiredAnnotationBeanPostProcesso. 67

What does @Autowired annotation mean?. 68

Explain @Qualifier annotation with example?. 69

How to use Spring @Component, @Repository, @Service and @Controller Annotations, @RequestMapping?. 70

Bean Lifecycle and Callbacks. 73

Initialization callbacks: 74

Destruction callbacks: 75

4 ways to schedule tasks in Spring 3 : @Scheduled example. 82

Explaining @Scheduled annotation. 82

Task scheduling using fixed delay attribute in @Scheduled annotation. 82

Task scheduling using cron expression in @Scheduled annotation. 82

Task scheduling using cron expression from properties file and @Scheduled annotation. 82

Task scheduling using cron expression configured in context configuration. 82

13 best practices for writing spring configuration files. 86

Spring MVC flow: 90

Spring MVC 3.2 Execution Flow.. 91

Defining a Controller. 93

Difference between context:component-scan and context:annotation-config in Spring. 93

Spring MVC: Difference between <context:annotation-config> vs <context:component-scan>. 94

Spring JdbcTemplate. 97

Problems of JDBC API 97

Spring Jdbc Approaches. 98

JdbcTemplate class. 98

Methods of spring JdbcTemplate class. 98

ResultSetExtractor Example | Fetching Records by Spring JdbcTemplate. 100

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 4/211 |

Page 5: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

RowMapper Example | Fetching records by Spring JdbcTemplate. 103

RowMapper Interface. 103

Advantage of RowMapper over ResultSetExtractor. 103

Method of RowMapper interface. 103

Example of RowMapper Interface to show all the records of the table. 104

Spring NamedParameterJdbcTemplate. 106

Spring SimpleJdbcTemplate. 108

Spring with ORM Frameworks. 110

Advantage of ORM Frameworks with Spring. 110

Hibernate and Spring Integration. 111

Advantage of Spring framework with hibernate. 111

Example of Hibernate and spring integration. 112

 

 

 

 

 

 

 

 

 

 

 

 

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 5/211 |

Page 6: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

 

 

 

 

 

 

Spring: (WHAT/WHEN/HOW/WHY)

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)

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

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 6/211 |

Page 7: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

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

When to use Spring.

What Are Spring Modules/Different modules of the spring frame work?

Spring Modules:-

Spring Core Model:-

This Core Module is the base module of a spring frame work application.

This Core Module will provide the following information to the spring programmers.

- The way of creating spring Beans.

- The way of Configuring Spring Beans.

- The way of injecting the dependencies.

- The way of obtaining a spring container object.

- The way of accessing the spring beans from container.

The core container provides the essential functionality of the Spring framework. A primary component of the core container is the

BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate

an application's configuration and dependency specification from the actual application code.

Spring DAO (JDBC) Module:-

This Module will provide an abstraction layer on top of JDBC technology.

While working with JDBC technology directly as programmers, we are writing the Boiler-plate code (Repeated code) like Loading

the driver, opening a connection, creating a statement and closing the objects etc?

Apart from Boiler-plate code, we also need to handle the Exceptions of JDBC explicitly because JDBC Exceptions are checked

exceptions.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 7/211 |

Page 8: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

In order to avoid the Boiler-plate code and to also avoid exception handling Burdon, spring frame work has provided this DAO

module.

The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error

messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of

exception code you need to write, such as opening and closing connections. Spring DAO's JDBC-oriented exceptions comply to its

generic DAO exception hierarchy.

Spring ORM Module:-

This ORM Module is an abstraction layer on top of the ORM tools and which makes a spring programmer to transfer a data between

application and database in the form of objects.

ORM tools are very good tools for communicating with databases but having some drawbacks, these drawbacks are eliminated in

spring ORM module.

The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including JDO, Hibernate, and

iBatis SQL Maps. All of these comply to Spring's generic transaction and DAO exception hierarchies.

Spring AOP Module:-

Aspect Oriented Programming is a new way to developing real time applications with required services

The AOP module will provide us the way of separating the services from Business logic and also it provides us the way of injecting

the services for business logic at runtime.

In spring terminology, the services are also called ?Cross-Cutting Concerns? (Middle ware services).

The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its

configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring

AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can

incorporate declarative transaction management into your applications without relying on EJB components.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 8/211 |

Page 9: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Spring JEE Module:-

This Module is for implementing the middleware services required for Business logic. This spring JEE module is an abstraction

layer on top of RMI, Java mail, JMS, Jars etc?

There is a difference between AOP and JEE modules

AOP is just for applying the services (or) injecting the services but not for implementing the services, whereas JEE is a module for

implementing the services.

For real time Business logic development with middleware services, we use spring core, spring AOP, and spring JEE modules.

The Model-View-Controller (MVC) framework is a full-featured MVC implementation for building Web applications. The MVC

framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity,

Tiles, iText, and POI.

Spring Web Module:-

This module is either for integrating with web applications created in other frame works (or) for creating complete MVC to based

web application in spring frame work.

Spring web module is also called Spring web MVC module and this module is for creating web applications of java with MVC to

architecture.

The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a

result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part

requests and binding request parameters to domain objects.

Spring Core Module, Spring IOC Tutorial

Name some of the design patterns used in Spring Framework?

There are loads of different design patterns used, but there are a few obvious ones:

Proxy -- used heavily in AOP, and remoting.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 9/211 |

Page 10: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Singleton -- beans defined in spring config files are singletons by default.

Template method -- used extensively to deal with boilerplate repeated code e.g. RestTemplate, JmsTemplate, JpaTemplate.

Front Controller -- Spring provides DispatcherServlet to ensure an incoming request gets dispatched to your controllers.

View Helper -- Spring has a number of custom JSP tags, and velocity macros, to assist in separating code from presentation in

views.

Dependency injection -- Center to the whole BeanFactory / ApplicationContext concepts.

Factory pattern -- BeanFactory for creating instance of an object.

What is IOC and Dependency Injection?

Inversion of control(IoC) is a programming technique in which object coupling is bound at run time by an assembler object and is

typically not known at compile time using static analysis.

What is Dependency Injection?

- Dependency Injection is a way to achieve Inversion of control (IoC) in our application by moving objects binding from

compile time to runtime. We can achieve IoC through Factory Pattern, Template Method Design Pattern, Strategy Pattern and

Service Locator pattern too.

- Spring, Google Guice and Java EE CDI frameworks facilitate the process of dependency injection through use of Java

Reflection API and java annotations. All we need is to annotate the field, constructor or setter method and configure them in

configuration xml files or classes.

Differentiating with dependency injection

Inversion of control is a design paradigm with the goal of giving more control to the targeted components of your application, the

ones getting the work done.

Dependency injection is a pattern used to create instances of objects that other objects rely on without knowing at compile time

which class will be used to provide that functionality. Inversion of control relies on dependency injection because a mechanism is

needed in order to activate the components providing the specific functionality.

The two concepts work together in this way to allow for much more flexible, reusable, and encapsulated code to be written. As such,

they are important concepts in designing object-oriented solutions.

Implementing inversion of control design pattern

In object-oriented programming, there are several basic techniques to implement inversion of control. These are:

- using a factory pattern

- using a service locator pattern

- using a dependency injection of any given below type:There are 3 types of dependency Injection.

Constructor Injection : Dependencies are provided as constructor parameters.

Setter Injection : Dependencies are assigned through JavaBeans properties (ex: setter methods).

Interface Injection: Injection is done through an interface.

Spring Hello World, Setter Injection With Primitive Values

Let us see the first program in spring, which is going to be the setter injection with some primitive values?

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 10/211 |

Page 11: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Files required..

- java

- java [ Our logic

- xml [ spring configuration file, it can be of any name

Open Eclipse ?> File ?> New ?> (Select Java project, if not found just click on) Other

Now choose ?> java project and click on next

Now it will ask you to give you application name, so give what ever name you want and click finish?

That's it.., now you will see your application will looks like this..

Of course i have been created the files in technicalstack package?..

Let us see the program files logic

WelcomeBean.java

package technicalstack;

public class WelcomeBean {

private String message;

public void setMessage(String message)

{

this.message = message;

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 11/211 |

Page 12: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

public void show()

{

System.out.println(message);

}

}

ClientLogic.java

package technicalstack;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.ClassPathResource;

import org.springframework.core.io.Resource;

public class ClientLogic {

public static void main(String[] args)

{

Resource res = new ClassPathResource("spconfig.xml");

BeanFactory factory = new XmlBeanFactory(res);

Object o = factory.getBean("id1");

WelcomeBean wb = (WelcomeBean)o;

wb.show();

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 12/211 |

Page 13: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

}

package technicalstack;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.ClassPathResource;

import org.springframework.core.io.Resource;

spconfig.xml

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"

"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>

<bean id="id1" class="technicalstack.WelcomeBean">

<property name="message" value="Welcome to spring" />

</bean>

</beans>

Explanation

see WelcomeBean.java, i have written setter method for the property message (primitive), spring container will inject some value in

that property at run time

In ClientLogic.java first we need to load the configuration file, so we done this at line number 12, so res, contains all the information

about the configuration xml.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 13/211 |

Page 14: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

And give this res object to BeanFactory [ Spring container ] with XmlBeanFactory, so now factory knows all the beans in the xml

file so we can now call any bean with bean id.

In ClientLogic.java, if we call getBean(?id1?) then internally the spring framework executes the following statements

WelcomeBean wb = new WelcomeBean();

wb.setMessage(?Welcome to spring?);

And now will gives WelcomeBean object back [at line number 15,] in the form of Object class object, and i typecast into

WelcomeBean class at line number 16

Remember, by default every spring bean is the singleton class.  Spring IOC container makes a spring bean as singleton automatically

Return type of getBean() is always super class object, which is Object class object

i have given that primitive type as String, you can use int, float, double what ever you want

See in spconfig.xml, line number 7 we have written the property element right, here <property />  means we are saying to the spring

container that we have written setter method in our bean class [WelcomeBean.java 7 to 9 lines ], in the that property we assigned

value as an attribute, which means the setter injection is in the form of primitive values [ may be int, string, float bla bla.. ]

Setter Injection With Objects, Spring Dependency In The Form Of Objects

?While constructing spring beans, if one spring bean is depends on another spring bean class for performing some logic, this process

of dependency is called object dependency?

If object dependency is there then in spring framework, the spring IOC container is responsible for creating that required object and

injecting into the dependent class

For spring configuration xml, we have 2 ways to inform to the spring container about this object dependency

- By using inner beans

- Using <ref /> element

Actually with inner beans we have some disadvantages and its not the way to use in the real time projects so am not going to explain

about it.

So we will see about <ref  /> element, and i forgot to tell you actually in previous example we have one spring configuration file

right [ spconfig.xml ], in spring we can write multiple configuration xmls, i will tell you how its going to work in the following

example

Using <ref /> element

Syntax will be

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 14/211 |

Page 15: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<ref local/parent/bean=?id of collaborator bean?>

Actually we used to write either local or parent or bean, means as i told you earlier, we can write any number of spring configuration

xmls for the spring application.  Our collaborator bean may be in same xml or other xml so spring has given these 3 options, we will

see one by one.

<ref local=?id value? />

If we use the local attribute in the <ref /> element then the spring IOC container will verify for the collaborator bean with in same

container [ i mean in same xml ]

In general we try to configure all spring beans into a single spring configuration xml only.  But its not mandatory we can create

multiple configure files too right.

Exmple:

public DemoBean

{

public SampleBean sb;

public void setSb(SampleBean sb)

{

this.sb = sb;

}

public void m1()

{

sb.m2();

}

}

Note: See am calling m2() method in SamepleBean so now let us see how the xml file will be

<beans>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 15/211 |

Page 16: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<bean id="id1">

<property name="sb" class="DemoBean">

<ref local="id2" />

</property>

</bean>

<bean id="id2" class="SampleBean">

</beans>

So our DemoBean class depends on other class object SampleBean,  see in the xml line number 5 i have specified ref tag with local

attribute and given that required class id, why local?? because that required (collaborator) class also i have configured in the same

xml file  [ line number 9 ], so spring container will check only in this xml only

<ref parent=?id value? />

But we can also configure the collaborator class in other xml like?

spconfig1.xml

<beans>

<bean id="id1">

<property name="sb" class="DemoBean">

<ref parent="id2" />

</property>

</bean>

spconfig2.xml

<beans>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 16/211 |

Page 17: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<bean id="id2" class="SampleBean">

</beans>

In this case, we have to write parent as attribute, see spconfig1.xml  line number 5.  As we specified parent, spring container will

only checks in the parent i mean spconfig2.xml only

If we give attribute as bean, then first it will checks at local xml file, then parent if its not available at local.  Hey you will be able to

understand once you got through the example?, let us see the program on this in the next session.

Let us see one example for previous concept, dependency in the form of objects with <ref /> element

files required..

i am taking complete pojo / poji model this time, And mates this is  ? very important and Exact concept of spring framework ? ,

make sure you understood this application from start to end point, if you are not able to understand you may not able to continue

with the remaining concepts :-)

i will try to explain clearly in my own way?.

- java

- java

- java

- java

- java

- xml

- xml

- java

Journey is the interface, and Traveler is the implemented class

Journey.java

public interface Journey

{

void startJournty();

}

Travel.java

public class Travel implements Journey

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 17/211 |

Page 18: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

{

Private Vehicle v;

public void setV(Vehicle v)

{

this.v = v;

}

public void startJorunty()

{

System.out.println("Journey been started....");

v.move();

}

}

Vehicle is the interface, Car and Bus are the implemented classes

See Traveler Class is depends on Vehicle object

Vehicle.java

public interface Vehicle

{

void move();

}

Car.java

package technicalstack;

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 18/211 |

Page 19: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

public class Car implements Vehicle{

private String fuelType;

private int maxSpeed;

public String getFuelType() {

return fuelType;

}

public void setFuelType(String fuelType) {

this.fuelType = fuelType;

}

public int getMaxSpeed() {

return maxSpeed;

}

public void setMaxSpeed(int maxSpeed) {

this.maxSpeed = maxSpeed;

}

public void move()

{

System.out.println("Fuel type :" +fuelType);

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 19/211 |

Page 20: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

System.out.println("max speed :" +maxSpeed);

System.out.println("car started....");

}

}

package technicalstack;

public class Car implements Vehicle{

private String fuelType;

private int maxSpeed;

public String getFuelType() {

return fuelType;

}

public void setFuelType(String fuelType) {

this.fuelType = fuelType;

}

public int getMaxSpeed() {

return maxSpeed;

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 20/211 |

Page 21: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

public void setMaxSpeed(int maxSpeed) {

this.maxSpeed = maxSpeed;

}

public void move()

{

System.out.println("Fuel type :" +fuelType);

System.out.println("max speed :" +maxSpeed);

System.out.println("car started....");

}

}

Bus

package technicalstack;

public class Bus implements Vehicle{

private int maxSpeed;

public int getMaxSpeed() {

return maxSpeed;

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 21/211 |

Page 22: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

public void setMaxSpeed(int maxSpeed) {

this.maxSpeed = maxSpeed;

}

public void move()

{

System.out.println("max speed :" +maxSpeed);

System.out.println("Bus started....");

}

}

spconfig1.xml

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"

"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>

<bean id="id1" class="technicalstack.Car">

<property name="fuelType" value="Diesel" />

<property name="maxSpeed" value="100" />

</bean>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 22/211 |

Page 23: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<bean id="id2" class="technicalstack.Bus">

<property name="maxSpeed" value="80" />

</bean>

</beans>

spconfig2.xml

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"

"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>

<bean id="id3" class="technicalstack.Travel">

<property name="v">

<ref parent="id2" />

</property>

</bean>

</beans>

ClientLogic.java

package technicalstack;

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 23/211 |

Page 24: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.ClassPathResource;

import org.springframework.core.io.Resource;

public class ClientLogic {

public static void main(String[] args)

{

Resource res1 = new ClassPathResource("spconfig1.xml");

BeanFactory factory1 = new XmlBeanFactory(res1);

Resource res2 = new ClassPathResource("spconfig2.xml");

BeanFactory factory2 = new XmlBeanFactory(res2,factory1);

Object o = factory2.getBean("id3");

Journey j = (Journey)o;

j.startJourney();

}

}

package technicalstack;

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 24/211 |

Page 25: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.ClassPathResource;

import org.springframework.core.io.Resource;

public class ClientLogic {

public static void main(String[] args)

{

Resource res1 = new ClassPathResource("spconfig1.xml");

BeanFactory factory1 = new XmlBeanFactory(res1);

Resource res2 = new ClassPathResource("spconfig2.xml");

BeanFactory factory2 = new XmlBeanFactory(res2,factory1);

Object o = factory2.getBean("id3");

Journey j = (Journey)o;

j.startJourney();

}

}

Explanation:

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 25/211 |

Page 26: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

ClientLogic.java is our client application, i mean it contains our business logic

Journey, Vehicle are two interfaces in our application

No confusion, i have taken all the classes with some implementation, i will tell you the reason why? ?

Now come to the configuration files, i have been taken 2 configuration xml (for explaining local, parent, bean attribute concept :) )

Now see execution flow?????.

Actually we have 2 configuration files right, so in our client logic we need to define factory object two times [ ClientLogic.java, line

numbers, 12,13 ? 15,16 ].  In factory1 object, i have been taken spconfig1.xml [ ClientLogic.java, Line number 12 ], where Car,Bus

classes been configured. factory2 knows factory1, as we included factory1 object in factory2 [ see line number 16, ClientLogic.java

]

Once we call id3 in ClientLogic.java, then spring container will move to spconfig2.xml and checks, there property v depends on

other class right, and we given parent=id2, then control move to spconfig1.xml and finds id2 ?> creates Bus class object, and will

send back that Bus object to our client program

According to our program Bus object will be injected into the Traveler finally and there after we will get it into client application,

and we can change id2 to id1 in the spconfig2.xml for getting Car object, with our recompilation ;)

Huuuu, mates hope you got what am saying, :-)

This is the complete POJO / POJI Model of spring, i will tell you why we need to take Interface for every class like above, you

might have known with this example, but no problem i will rise this topic in the next sessions.

Output:

Spring Setter Injection, Dependency In The Form Of Collections

While creating spring bean (pojo class), the bean class can use any of the following

4 types of collections as dependency, along with some primitives and objects like previous sessions..

- Set

- List

- Map

- Properties

Spring supports these 4 collections only as the dependencies.

Except above 4 types of collections, if the spring bean class uses any other type of collection as dependency, then spring container

doesn't inject that collection object to the spring bean, in this case spring programmer is responsible for injection that collection

object manually.

Let us see how to use one by one collection property with syntax

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 26/211 |

Page 27: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Spring Dependency Injection With Set Collection Property

Let us see few points, if we have Set property in our program

If in our spring bean has a property of type Set then in the spring config xml file, we need to use <set> element to inform the Spring

IOC container regarding that Set property

In spring config xml, we can use <value /> and <ref /> tags as sub elements of <set> tag

While configuring <set> in xml file it doesnt allow duplicate values, because Set collection is a unique collection

In spring framework if one bean is collaborating[depends on] with other bean class then  spring ioc container first creates

collaborator bean object after only dependent bean object

Example

public class SampleBean

{

private Set studentsData;

private TestBean tb;

public void setStudentsData(Set studentsData)

{

this.studentsData = studentsData;

}

public void setTb(TestBean tb)

{

this.tb = tb;

}

public void m1()

{

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 27/211 |

Page 28: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

// Some Logic

}

}

Our XML

<beans>

<bean id="id1" class="SampleBean">

<property name="studentsData">

<set>

<value>sun</value>

<value>Oracle</value>

<value>technicalstack</value>

<ref bean="id2">

</set>

</property>

</bean>

<bean id="id2" class="TestBean"/>

</beans>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 28/211 |

Page 29: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Explanation:

Now in our client when we call getBean(?id1?) then spring framework executes, following code internally [ not be visible :-) ]

TestBean tb = new TestBean();

Set s = new HastSet();

s.add("sun");

s.add("oracle");

s.add("technicalstack");

SampleBean ob =new SampleBean();

ob.setStudentsData(s);

TestBean tb = new TestBean();

Set s = new HastSet();

s.add("sun");

s.add("oracle");

s.add("technicalstack");

SampleBean ob =new SampleBean();

ob.setStudentsData(s);

First spring ioc creates TestBean class object as SampleBean depends on TestBean, then creates the Set object and will add the data

into the set object and finally our SampleBean object will be created and set object will be injected.

Actually nothing mates,  just like primitive value injections, just we used Collections here nothing more than that :-) , download this

example and test.

Complete Example On Spring Setter Injection With Set Collection Property

files will be used..

- java

- java

- xml

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 29/211 |

Page 30: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Directory structure:

WelcomeBean.java

package technicalstack;

import java.util.Set;

public class WelcomeBean {

private Set studentsData;

public void setStudentsData(Set studentsData) {

this.studentsData = studentsData;

}

public void show()

{

System.out.println(studentsData);

}

}

spconfig.xml

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 30/211 |

Page 31: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"

"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>

<bean id="id1" class="technicalstack.WelcomeBean">

<property name="studentsData" >

<set>

<value>technicalstack</value>

<value>sun</value>

<value>oracle</value>

<value>sun</value>

<value>sun</value>

</set>

</property>

</bean>

</beans>

ClientLogic.java

package technicalstack;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.ClassPathResource;

import org.springframework.core.io.Resource;

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 31/211 |

Page 32: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

public class ClientLogic {

public static void main(String[] args)

{

Resource res = new ClassPathResource("spconfig.xml");

BeanFactory factory = new XmlBeanFactory(res);

Object o = factory.getBean("id1");

WelcomeBean wb = (WelcomeBean)o;

wb.show();

}

}

Note:  Set wont allows duplicates, though you give duplicate values in spconfig.xml it will shows values only once in the output try

this ;)

OutPut

Spring Dependency Injection with List Collection Property

This is same as <set />, right previous session, but few changes are there, let us see the difference between these two <set /> and

<list />

In the previous example [ Dependency In The Form Of Set Collection Property ] just change to <list /> where ever we have <set />

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 32/211 |

Page 33: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Set doesn't allows duplicate right.., but List will allows duplicate values too

Create List object like,  List l= new ArrayList()

Set cannot put values in order, but List will keep the added values in the same order

If you still need the syntax just see

public class SampleBean

{

private List studentsData;

private TestBean tb;

public void setStudentsData(Set studentsData)

{

this.studentsData = studentsData;

}

public void setTb(TestBean tb)

{

this.tb = tb;

}

public void m1()

{

// Some Logic

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 33/211 |

Page 34: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

}

Our XML

<beans>

<bean id="id1" class="SampleBean">

<property name="studentsData">

<list>

<value>sun</value>

<value>Oracle</value>

<value>technicalstack</value>

<value>sun</value>

<ref bean="id2">

</list>

</property>

</bean>

<bean id="id2" class="TestBean"/>

</beans>

Note: Mates see, in our xml i have been added sun two times, as List will allows the duplicate values, but set doesn't.  That's it

mates, but Map is not like these two collection and little more important than these two, so we will see in depth regarding this Map

in the next session.

Mates am not giving any example here as its same as setter injection ( Hello World program only, see how easy ;) ),  but you can

download the example and test at your locals.

Complete Example On Spring Setter Injection With List Collection

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 34/211 |

Page 35: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

files will be used..

- java

- java

- xml

Directory structure:

WelcomeBean.java

package technicalstack;

import java.util.List;

public class WelcomeBean {

private List studentsData;

public void setStudentsData(List studentsData) {

this.studentsData = studentsData;

}

public void show()

{

System.out.println(studentsData);

}

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 35/211 |

Page 36: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

spconfig.xml

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"

"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>

<bean id="id1" class="technicalstack.WelcomeBean">

<property name="studentsData" >

<list>

<value>technicalstack</value>

<value>sun</value>

<value>oracle</value>

<value>technicalstack</value>

</list>

</property>

</bean>

</beans>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"

"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>

<bean id="id1" class="technicalstack.WelcomeBean">

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 36/211 |

Page 37: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<property name="studentsData" >

<list>

<value>technicalstack</value>

<value>sun</value>

<value>oracle</value>

<value>technicalstack</value>

</list>

</property>

</bean>

</beans>

ClientLogic.java

package technicalstack;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.ClassPathResource;

import org.springframework.core.io.Resource;

public class ClientLogic {

public static void main(String[] args)

{

Resource res = new ClassPathResource("spconfig.xml");

BeanFactory factory = new XmlBeanFactory(res);

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 37/211 |

Page 38: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Object o = factory.getBean("id1");

WelcomeBean wb = (WelcomeBean)o;

wb.show();

}

}

OutPut

Spring Dependency Injection With Map Collection Property

Map will stores the data in key, value base that to key, value must be the objects of any type.  One [ key, value ] is called one pair or

one entry.

k1            Oracle

k2            Sun

k3            technicalstack

k4            id2

See here we have two entries [two pairs], one entry is k1  ? 100 and second entry is k2   ? 200

Let us come to the concept, Map.Entry will gives one entry

Map is the interface, Entry is the static class in Map interface, so we can call Map.Entry just remember this concept as of now

Actually In this spring we always use Map.Entry class object only

In the XML

<map>

<entry key="k1">

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 38/211 |

Page 39: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<value>Oracle</value>

</entry>

<entry key="k2">

<value>Sun</value>

</entry>

<entry key="k3">

<value>technicalstack</value>

</entry>

<entry key="k4" value-ref="id2" />

</map>

See in the xml, we have to configure like this, so we have 3 pairs [ key, values] means spring container will creates 3 Map.Entry

class objects and stores those objects in <map />

One <entry /> tag will produces one object of Map.Entry, by the way k4 is to getting other bean class object.

Complete Example Using Map Collection[Repeat

files will be used..

- java

- java

- xml

Directory structure:

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 39/211 |

Page 40: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

WelcomeBean.java

package technicalstack;

import java.util.Iterator;

import java.util.Map;

import java.util.Set;

public class WelcomeBean {

private Map data;

public void setData(Map data) {

this.data = data;

}

public void show()

{

Set s=data.entrySet();

Iterator it = s.iterator();

while(it.hasNext())

{

Map.Entry me = (Map.Entry)it.next();

System.out.println(me.getKey()+ " - "+me.getValue());

}

}

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 40/211 |

Page 41: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

spconfig.xml

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"

"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>

<bean id="id1" class="technicalstack.WelcomeBean">

<property name="data" >

<map>

<entry key="k1">

<value>10</value>

</entry>

<entry key="k2">

<value>technicalstack</value>

</entry>

<entry key="k3">

<value>10.55</value>

</entry>

</map>

</property>

</bean>

</beans>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 41/211 |

Page 42: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

ClientLogic.java

package technicalstack;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.ClassPathResource;

import org.springframework.core.io.Resource;

public class ClientLogic {

public static void main(String[] args)

{

Resource res = new ClassPathResource("spconfig.xml");

BeanFactory factory = new XmlBeanFactory(res);

Object o = factory.getBean("id1");

WelcomeBean wb = (WelcomeBean)o;

wb.show();

}

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 42/211 |

Page 43: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Explanation:

First take our ClientLogic.java, see line number 15 when we call factory.getBean(?id1?) then spring IOC will go to spconfig.xml

and verify the class name having id1,  [ you can see this in spconfig.xml line number 5, there our class name is WelcomeBean ]

Now it will jumps to WelcomeBean.java

In WelcomeBean.java we have been taken Map property [ see line number 7 ], and written setter property for that Map

In spconfig.xml we configured some values for that Map property right, so with this setter method spring IOC will inject all these

values into Map data property

now come to show() method at line number 13, here see the concept actually we don't have any iterator for Map right, hope you

know this fact :-)  , but we need iterator to get and print the data from the Map, moreover List,Set have the iterator.

So now we need Set or List to get the iterator,  so am going to take Set, at line number 15, of course you can go with List as well

Actually data is of Map type, in Map we have one method called entrySet() which always returns Set object, so i got the iterator by

using this Set object at line number 16

Now see line number 19, i have been typecast into Map.Entry, so that i can print key and values separately by calling getKey() and

getValues() methods in the Map.Entry Class [ I already given the concept about this Map.Entry go to top and check if you have any

doubt regarding this ]

And we done :-)

And mates this Map having much importance in java remember?.!!!!!!

Constructor Injection In Spring [ Full Concept ]

In this type of injection spring container uses constructor of the bean class for assigning the dependencies. In spring config xml, we

need to inform to the spring IOC container about constructor injection by using <constructor -arg />

In spring bean class, if both constructor and setter injection applied for same property then constructor injection will be overridden

by setter injection, because constructor injection will happen at the object creation time, and setter after objection right?, so setter

will overrides

For Example:

public class DemoBean

{

public string message;

public DemoBean (String message)

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 43/211 |

Page 44: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

{

This.message = message;

}

public void setMessage(String message)

{

This.message = message;

}

public void show()

{

System.out.println("some logic here");

}

}

In Config XML

<bean id="id1" class="DemoBean">

<constructor-arg value="Welcome to technicalstack" />

<property name="message" value="Welcome to spring" />

</bean>

Output

In client application, when we call factory.getBean(?id1?), then internally spring framework executes following statements

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 44/211 |

Page 45: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

DemoBean ob = new DemoBean("Welcome to technicalstack");

Ob.setMessage("Welcome to spring");

finally value in message will be  Welcome to spring, not Welcome to technicalstack, as setter will over rides constructor, the reason

being see i have taken primitive value [string] as dependency,  we have written injection for this property in constructor and setter

method.  We all know constructor will be executed at object creation, so at the time of object creation only some value will be

assigned into message property, then setter will be called so previous value will be overrides

???????????? # ???????????

In constructor injection,  if argument types  are different, then at the time of configuring of xml file we can use type attribute

Example..

public class DemoBean

{

public int id;

public String sname;

public DemoBean(int id, string sname)

{

This.id  = id;

This.sname = sname;

}

}

In Config XML

<bean id="id1" class="DemoBean">

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 45/211 |

Page 46: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<constructor-arg type="java.lang.string" value="1000" />

<constructor-arg  value="10" />

</bean>

According to above xml, DemoBean object will be created with 10 as id and 1000 as string [sname]

???????????? # ???????????

Let if we have 2 properties of same type, like user name and password

Example..

public class DemoBean

{

public String uname, password;

public DemoBean (String uname, String password)

{

This.uname = uname;

This.password = password;

}

}

In our xml

<bean id="id1" class="DemoBean">

<constructor-arg value="myuserName"  index="0" />

<constructor-arg value="mypassword"  index="1" />

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 46/211 |

Page 47: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Now bean object will be created with myuserName as username, and mypassword as password

???????????? # ???????????

Dependency in the form of object in this constructor injection

Let us see how to work with dependency in the form of objects in this constructor injection?

public class DemoBean

{

public SampleBean sb;

public DemoBean(SampleBean sb)

{

This.sb = sb;

}

}

In the xml

<bean id="id1" class="DemoBean">

<constructor-arg ref="sb" />

</bean>

<bean id="sb" class="SampleBean" />

1

2

3

4

<bean id="id1" class="DemoBean">

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 47/211 |

Page 48: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<constructor-arg ref="sb" />

</bean>

<bean id="sb" class="SampleBean" />

Note: Here see, directly i given ref as an attribute, so internally it meas ref-bean only not ref-local or ref-parent

???????????? # ???????????

If we have multiple constructors then..

public class DemoBean

{

public String uname, password;

public DemoBean (int id, String uname)

{

This.id = id;

This.uname = uname;

}

public DemoBean (string uname, int id)

{

This.id = id;

This.uname = uname;

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 48/211 |

Page 49: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

public class DemoBean

{

public String uname, password;

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 49/211 |

Page 50: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

public DemoBean (int id, String uname)

{

This.id = id;

This.uname = uname;

}

public DemoBean (string uname, int id)

{

This.id = id;

This.uname = uname;

}

}

XML file will be

<beans>

<bean id="id1" class="DemoBean">

<constructor-arg value="10" />

<constructor-arg value="MyUserName" type="java.lang.string"/>

</bean>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 50/211 |

Page 51: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<bean id="id2" class="DemoBean">

<constructor-arg value="MyUserName" />

<constructor-arg value="10" />

</bean>

</beans>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 51/211 |

Page 52: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<beans>

<bean id="id1" class="DemoBean">

<constructor-arg value="10" />

<constructor-arg value="MyUserName" type="java.lang.string"/>

</bean>

<bean id="id2" class="DemoBean">

<constructor-arg value="MyUserName" />

<constructor-arg value="10" />

</bean>

</beans>

In the above example, when we class factory.getBean(?id1?) from client application then spring framework creates an object of

DemoBean by calling 1st constructure

If we call factory.getBean(?id2?) then spring framework crates the object of DemoBean by calling 2nd constructor automatically

This is total about this constructor injection in Spring, nothing more than that.

Difference between Setter Injection and Constructor Injection

 

How to inject a java.util.Properties into a Spring Bean?

First way is to use <props> tag as below.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 52/211 |

Page 53: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<bean id="adminUser" class="com.technicalstack.common.Customer">

<!-- java.util.Properties -->

<property name="emails">

<props>

<prop key="admin">[email protected]</prop>

<prop key="support">[email protected]</prop>

</props>

</property>

</bean>

You can use ?util:? namespace as well to create properties bean from properties file, and use bean reference for setter injection.

<util:properties id="emails" location="classpath:com/foo/emails.properties" />

IoC containers:

The org.springframework.beans and org.springframework.context packages provide the basis for the Spring Framework's IoC

container.

The org.springframework.beans.factory.BeanFactory is the actual representation of the Spring IoC container that is responsiblefor containing and otherwise managing the aforementioned beans. The BeanFactory interface is the central IoC containerinterface in Spring.

 There are two types of IoC containers:

Bean Factory container:This is the simplest container providing basic support for DI .The BeanFactory is usually preferred where

the resources are limited like mobile devices or applet based applications

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.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 53/211 |

Page 54: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans

within itself and then instantiates the bean whenever asked for by clients.BeanFactory is able to create associations between

collaborating objects as they are instantiated. This removes the burden of configuration from bean itself and the beans

client. BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.

On the surface, an application context is same as a bean factory.Both load bean definitions, wire beans together, and dispense beans

upon request. But it also provides:

- A means for resolving text messages, including support for internationalization.

- A generic way to load file resources.

- Events to beans that are registered as listeners.

Implementation of BeanFactory

The most commonly used BeanFactory implementation is theXmlBeanFactory  This container reads the configuration metadata

from an XML file and uses it to create a fully configured system or application.

 

Implementations of ApplicationContext (The three commonly used))

The most commonly used ApplicationContext implementations are:

FileSystemXmlApplicationContext: This container loads the definitions of the beans from an XML file. Here you need to provide

the full path of the XML bean configuration file to the constructor.

-

FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("F:/my workspace/springAppDemo/sr

c/spring.xml");

Using wildcard for file system:FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("F:/*my workspace*/**/src/*-spring.xml");

ClassPathXmlApplicationContext This container loads the definitions of the beans from an XML file. Here you do not need to

provide the full path of the XML file but you need to set CLASSPATH properly because this container will look bean configuration

XML file in CLASSPATH.

-

ApplicationContext context = new ClassPathXmlApplicationContext("classpath:com/dineshonjava/sdnext/springConfig/sprin

g.xml");

Using wildcard for claspath:

-

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 54/211 |

Page 55: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:com/dineshonjava/**/springConfig/spring.

xml");

- ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:com/*/**/springConfig/*-spring.xml");

WebXmlApplicationContext: This container loads the XML file with definitions of all beans from within a web application.

- ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);

What is the difference between Bean Factory and Application Context ?

On the surface, an application context is same as a bean factory. But application context offers much more..

- Application contexts provide a means for resolving text messages, including support for i18n of those messages.

- Application contexts provide a generic way to load file resources, such as images.

- Application contexts can publish events to beans that are registered as listeners.

- Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a

bean factory, can be handled declaratively in an application context.

- ResourceLoader support: Spring's Resource interface us a flexible generic abstraction for handling low-level resources. An

application context itself is a ResourceLoader, Hence provides an application with access to deployment-specific Resource

instances.

- MessageSource support: The application context implements MessageSource, an interface used to obtain localized

messages, with the actual implementation being pluggable

What are Spring beans?

- 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, for example, in the form of XML <bean/> definitions.

What does a bean definition contain?

- The bean definition contains the information called configuration metadata which is needed for the container to know the

followings:

- How to create a bean

- Bean's lifecycle details

- Bean's dependencies

How do you provide configuration metadata to the Spring Container?

There are following three important methods to provide configuration metadata to the Spring Container:

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 55/211 |

Page 56: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

- XML based configuration file.

- Annotation-based configuration

- Java-based configuration

How do add a bean in spring application?

Check the following 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.xsd">

<bean id="helloWorld" class="com.tutorialspoint.HelloWorld">

<property name="message" value="Hello World!"/>

</bean>

</beans>

How do you define a bean scope?

When defining a <bean> in Spring, you have the option of declaring a scope for that bean. For example, to force Spring to produce

a new bean instance each time one is needed, you should declare the bean's scope attribute to be prototype. Similar way if you want

Spring to return the same bean instance each time one is needed, you should declare the bean's scope attribute to be

Ways to instantiate beans in spring

A bean definition can be seen as a recipe for creating one or more actual objects. The container looks at the recipe for a named bean

when asked, and uses the configuration metadata encapsulated by that bean definition to create (or acquire) an actual object.

1.       Instantiation using a constructor

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 56/211 |

Page 57: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

When creating a bean using the constructor approach, all normal classes are usable by and compatible with Spring. That is, the class

being created does not need to implement any specific interfaces or be coded in a specific fashion. Just specifying the bean class

should be enough. When using XML-based configuration metadata you can specify your bean class like so:

<bean id="exampleBean"/>

2.       Instantiation using a static factory method

When defining a bean which is to be created using a static factory method, along with the class attribute which specifies the class

containing the static factory method, another attribute named factory-method is needed to specify the name of the factory method

itself.

<bean id="exampleBean" factory-method="createInstance"/>

Spring expects to be able to call this method and get back a live object, which from that point on is treated as if it had been created

normally via a constructor.

3.       Instantiation using an instance factory method

In a fashion similar to instantiation via a static factory method, instantiation using an instance factory method is where the factory

method of an existing bean from the container is invoked to create the new bean.

<bean id="myFactoryBean"  class="...">

<bean id="exampleBean"  factory-bean="myFactoryBean"

factory-method="createInstance"></bean>

Various dependency injection mechanisms

The basic principle behind Dependency Injection (DI) is that objects define their dependencies only through constructor arguments,

arguments to a factory method, or properties which are set on the object instance after it has been constructed or returned from a

factory method. Then, it is the job of the container to actually inject those dependencies when it creates the bean. This is

fundamentally the inverse, hence the name Inversion of Control (IoC).

4.       Setter injection

Setter-based DI is realized by calling setter methods on your beans after invoking a no-argument constructor or no-argument static

factory method to instantiate your bean.

public class TestSetter {

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 57/211 |

Page 58: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

DemoBean demoBean = null;

public void setDemoBean(DemoBean demoBean) {

this.demoBean = demoBean;

}

}

5.       Constructor injection

Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator.

Additionally, calling a static factory method with specific arguments to construct the bean, can be considered almost equivalent, and

the rest of this text will consider arguments to a constructor and arguments to a static factory method similarly.

Interface injection In this methodology we implement an interface from the IOC framework. IOC framework will use the interface

method to inject the object in the main class. It is much more appropriate to use this approach when you need to have some logic that

is not applicable to place in a property. Such as logging support.

public void SetLogger(ILogger logger)

{

_notificationService.SetLogger(logger);

_productService.SetLogger(logger);

}

What is difference between component and service?

A component is a glob of software that's intended to be used, without change, by an application that is out of the control of the

writers of the component. By ?without change' means that the using application doesn't change the source code of the components,

although they may alter the component's behavior by extending it in ways allowed by the component writers.

A service is similar to a component in that it's used by foreign applications. The main difference is that a component to be used

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 58/211 |

Page 59: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

locally (think jar file, assembly, dll, or a source import). A service will be used remotely through some remote interface, either

synchronous or asynchronous (eg web service, messaging system, RPC, or socket.)

How DI is different from Service locator pattern?

The key benefit of a Dependency Injector is that it allows to plug-in a suitable implementation of a service according to environment

and usage. Injection isn't the only way to break this dependency, another is to use a service locator. The basic idea behind a service

locator is to have an object that knows how to get hold of all of the services that an application might need. It then scans all such

services and store them as a singleton Registry. When asked for a service implementation, a requester can query the registry with a

token and get appropriate implementation.

Mostly these registries are populated via some configuration files. The key difference is that with a Service Locator every user of a

service has a dependency to the locator. The locator can hide dependencies to other implementations, but you do need to see the

locator.

Which one should be better to use i.e. service locator or dependency injection?

Well, it as I already said that key difference is that with a Service Locator every user of a service has a dependency to the locator. It

means you must know the details of service locator in terms of input and output. So, it actually becomes the deciding factor which

pattern to choose from.

If it is easy and necessary to maintain registry information then go for service locator, or else simply use dependency injection as it

does not bother the users of service with any per-requisites.

Which is better constructor injection or setter injection?

The choice between setter and constructor injection is interesting as it mirrors a more general issue with object-oriented

programming -- should you fill fields in a constructor or with setters.

Constructors with parameters give you a clear statement of what it means to create a valid object in an obvious place. If there's more

than one way to do it, create multiple constructors that show the different combinations. Another advantage with constructor

initialization is that it allows you to clearly hide any fields that are immutable by simply not providing a setter. I think this is

important -- if something shouldn't change then the lack of a setter communicates this very well. If you use setters for initialization,

then this can become a pain.

But If you have a lot of constructor parameters things can look messy, particularly in languages without keyword parameters. If you

have multiple ways to construct a valid object, it can be hard to show this through constructors, since constructors can only vary on

the number and type of parameters. Constructors also suffer if you have simple parameters such as strings. With setter injection you

can give each setter a name to indicate what the string is supposed to do. With constructors you are just relying on the position,

which is harder to follow.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 59/211 |

Page 60: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

My preference is to start with constructor injection, but be ready to switch to setter injection as soon as the problems I've outlined

above start to become a problem.

What bean scopes does Spring support? Explain them.

- The Spring Framework supports following five scopes, three of which are available only if you use a web-aware

ApplicationContext.

singleton:This scopes the bean definition to a single instance per Spring IoC container.

prototype:This scopes a single bean definition to have any number of object instances.

request:This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.

session:This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.

global-session:This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring

ApplicationContext.

What is default scope of bean in Spring framework?

- The default scope of bean is Singleton for Spring framework.

Are Singleton beans thread safe in Spring Framework?

- No, singleton beans are not thread-safe in Spring framework.

What are different ways to configure a class as Spring Bean?

There are three different ways to configure Spring Bean.

XML Configuration: This is the most popular configuration and we can use bean element in context file to configure a Spring

Bean. For example:

<bean name="myBean" class="com.journaldev.spring.beans.MyBean"></bean>

Java Based Configuration: If you are using only annotations, you can configure a Spring bean using @Bean annotation. This

annotation is used with @Configuration classes to configure a spring bean. Sample configuration is:

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 60/211 |

Page 61: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

@Configuration

@ComponentScan(value="com.journaldev.spring.main")

public class MyConfiguration {

@Bean

public MyService getService(){

return new MyService();

}

}

To get this bean from spring context, we need to use following code snippet:

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(

MyConfiguration.class);

MyService service = ctx.getBean(MyService.class);

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 61/211 |

Page 62: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Annotation Based Configuration: We can also use @Component, @Service, @Repository and @Controller annotations with

classes to configure them to be as spring bean. For these, we would need to provide base package location to scan for these classes.

For example:

1

<context:component-scan base-package="com.journaldev.spring" />

 

 What are different scopes of Spring Bean?

There are five scopes defined for Spring Beans.

singleton: Only one instance of the bean will be created for each container. This is the default scope for the spring beans. While

using this scope, make sure spring bean doesn't have shared instance variables otherwise it might lead to data inconsistency issues

because it's not thread-safe.

prototype: A new instance will be created every time the bean is requested.

request: This is same as prototype scope, however it's meant to be used for web applications. A new instance of the bean will be

created for each HTTP request.

session: A new bean will be created for each HTTP session by the container.

global-session: This is used to create global session beans for Portlet applications.

Spring Framework is extendable and we can create our own scopes too, however most of the times we are good with the scopes

provided by the framework.

To set spring bean scopes we can use ?scope? attribute in bean element or @Scope annotation for annotation based configurations.

What is Spring Java-Based Configuration?

The central artifacts in Spring's new Java-configuration support are @Configuration annotated classes and @Bean annotated

methods.

The @Bean annotation is used to indicate that a method instantiates, configures and initializes a new object to be managed by the

Spring IoC container. @Bean annotation plays the same role as the <bean/> element.

Annotating a class with @Configuration indicates that its primary purpose is as a source of bean definitions. Furthermore,

@Configuration classes allow inter-bean dependencies to be defined by simply calling other @Bean methods in the same class. The

simplest possible @Configuration class would read as follows:

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 62/211 |

Page 63: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

@Configuration

public class AppConfig

{

@Bean

public MyService myService() {

return new MyServiceImpl();

}

}

The equivalent XML configuration for above java config would be:

<beans>

<bean id="myService" class="com.technicalstack.services.MyServiceImpl"/>

</beans>

To instantiate such config, you will need the help of AnnotationConfigApplicationContext class.

public static void main(String[] args) {

ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);

MyService myService = ctx.getBean(MyService.class);

myService.doStuff();

}

To enable component scanning, just annotate your @Configuration class as follows:

@Configuration

@ComponentScan(basePackages = "com.technicalstack")

public class AppConfig  {

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 63/211 |

Page 64: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

...

}

In the example above, the com.acme package will be scanned, looking for any @Component annotated classes, and those classes

will be registered as Spring bean definitions within the container.

If you are using above configuration in a web application then you will be using AnnotationConfigWebApplicationContext class.

This implementation may be used when configuring the Spring ContextLoaderListener servlet listener, Spring MVC

DispatcherServlet etc.

<web-app>

<!-- Configure ContextLoaderListener to use AnnotationConfigWebApplicationContext

instead of the default XmlWebApplicationContext -->

<context-param>

<param-name>contextClass</param-name>

<param-value>

org.springframework.web.context.support.AnnotationConfigWebApplicationContext

</param-value>

</context-param>

<!-- Configuration locations must consist of one or more comma- or space-delimited

fully-qualified @Configuration classes. Fully-qualified packages may also be

specified for component-scanning -->

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>com.technicalstack.AppConfig</param-value>

</context-param>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 64/211 |

Page 65: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<!-- Bootstrap the root application context as usual using ContextLoaderListener -->

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

<!-- Declare a Spring MVC DispatcherServlet as usual -->

<servlet>

<servlet-name>dispatcher</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<!-- Configure DispatcherServlet to use AnnotationConfigWebApplicationContext

instead of the default XmlWebApplicationContext -->

<init-param>

<param-name>contextClass</param-name>

<param-value>

org.springframework.web.context.support.AnnotationConfigWebApplicationContext

</param-value>

</init-param>

<!-- Again, config locations must consist of one or more comma- or space-delimited

and fully-qualified @Configuration classes -->

<init-param>

<param-name>contextConfigLocation</param-name>

<param-value>com.technicalstack.web.MvcConfig</param-value>

</init-param>

</servlet>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 65/211 |

Page 66: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<!-- map all requests for /app/* to the dispatcher servlet -->

<servlet-mapping>

<servlet-name>dispatcher</servlet-name>

<url-pattern>/app/*</url-pattern>

</servlet-mapping>

</web-app>

What is Spring 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 to have following configuration file in case you want to use any annotation

in your Spring application.

<beans>

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

Few important annotations which you will be using in this type of configuration are :

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 66/211 |

Page 67: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

@Required : The @Required annotation applies to bean property setter methods.

@Autowired : The @Autowired annotation can apply to bean property setter methods, non-setter methods, constructor and

properties.

@Qualifier : The @Qualifier annotation along with @Autowired can be used to remove the confusion by specifiying which exact

bean will be wired.

JSR-250 Annotations : Spring supports JSR-250 based annotations which include @Resource, @PostConstruct and @PreDestroy

annotations.

What is Spring Bean life cycle?

The life cycle of a Spring bean is easy to understand. When a bean is instantiated, it may be required to perform some initialization

to get it into a usable state. Similarly, when the bean is no longer required and is removed from the container, some cleanup may be

required.

Spring bean factory is responsible for managing the life cycle of beans created through spring container. The life cycle of beans

consist of call back methods which can be categorized broadly in two groups:

- Post initialization call back methods

- Pre destruction call back methods

Spring framework provides following 4 ways for controlling life cycle events of bean:

- InitializingBean and DisposableBean callback interfaces

- Other Aware interfaces for specific behavior

- Custom init() and destroy() methods in bean configuration file

- @PostConstruct and @PreDestroy annotations

For example, customInit() and customDestroy() methods are example of life cycle method.

<beans>

<bean id="demoBean" class="com.technicalstack.task.DemoBean"

init-method="customInit" destroy-method="customDestroy"></bean>

</beans>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 67/211 |

Page 68: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

How to get ServletContext and ServletConfig object in a Spring Bean?

There are two ways to get Container specific objects in the spring bean.

- Implementing Spring *Aware interfaces, for these ServletContextAware and ServletConfigAware interfaces, for complete

example of these aware interfaces, please read Spring Aware Interfaces]

- Using @Autowired annotation with bean variable of type ServletContext and ServletConfig. They will work only in servlet

container specific environment only though.

1

2

@Autowired

ServletContext servletContext;

 Spring Bean Life Cycle Methods ? InitializingBean, DisposableBean, @PostConstruct, @PreDestroy and *Aware interfaces

Spring Beans are the most important part of any Spring application. Spring ApplicationContext is responsible to initialize the Spring

Beans defined in spring bean configuration file.

Spring Context is also responsible for injection dependencies in the bean, either through setter/constructor methods or by spring

autowiring.

Sometimes we want to initialize resources in the bean classes, for example creating database connections or validating third party

services at the time of initialization before any client request. Spring framework provide different ways through which we can

provide post-initialization and pre-destroy methods in a spring bean.

By implementing InitializingBean and DisposableBean interfaces ? Both these interfaces declare a single method where we can

initialize/close resources in the bean. For post-initialization, we can implement InitializingBean interface and provide

implementation of afterPropertiesSet() method. For pre-destroy, we can implement DisposableBean interface and provide

implementation of destroy() method. These methods are the callback methods and similar to servlet listener implementations.

This approach is simple to use but it's not recommended because it will create tight coupling with the Spring framework in our bean

implementations.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 68/211 |

Page 69: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Providing init-method and destroy-method attribute values for the bean in the spring bean configuration file. This is the

recommended approach because of no direct dependency to spring framework and we can create our own methods.

Note that both post-init and pre-destroy methods should have no arguments but they can throw Exceptions. We would also require to

get the bean instance from the spring application context for these methods invocation.

@PostConstruct and @PreDestroy Annotations

Spring framework also support @PostConstruct and @PreDestroy annotations for defining post-init and pre-destroy methods. These

annotations are part of javax.annotation package. However for these annotations to work, we need to configure our spring

application to look for annotations. We can do this either by defining bean of type

org.springframework.context.annotation.CommonAnnotationBeanPostProcessor or by context:annotation-config element in spring

bean configuration file.

Let's write a simple Spring application to showcase the use of above configurations. Create a Spring Maven project in Spring Tool

Suite, final project will look like below image.

spring-bean-life-cycle-project

Spring Maven Dependencies

We don't need to include any extra dependencies for configuring spring bean life cycle methods, our pom.xml file is like any other

standard spring maven project.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 69/211 |

Page 70: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<modelVersion>4.0.0</modelVersion>

<groupId>org.springframework.samples</groupId>

<artifactId>SpringBeanLifeCycle</artifactId>

<version>0.0.1-SNAPSHOT</version>

<properties>

<!-- Generic properties -->

<java.version>1.7</java.version>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

<!-- Spring -->

<spring-framework.version>4.0.2.RELEASE</spring-framework.version>

<!-- Logging -->

<logback.version>1.0.13</logback.version>

<slf4j.version>1.7.5</slf4j.version>

</properties>

<dependencies>

<!-- Spring and Transactions -->

<dependency>

<groupId>org.springframework</groupId>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 70/211 |

Page 71: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<artifactId>spring-context</artifactId>

<version>${spring-framework.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-tx</artifactId>

<version>${spring-framework.version}</version>

</dependency>

<!-- Logging with SLF4J & LogBack -->

<dependency>

<groupId>org.slf4j</groupId>

<artifactId>slf4j-api</artifactId>

<version>${slf4j.version}</version>

<scope>compile</scope>

</dependency>

<dependency>

<groupId>ch.qos.logback</groupId>

<artifactId>logback-classic</artifactId>

<version>${logback.version}</version>

<scope>runtime</scope>

</dependency>

</dependencies>

</project>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 71/211 |

Page 72: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Model Class

Let's create a simple java bean class that will be used in service classes.

Employee.java

package com.journaldev.spring.bean;

public class Employee {

private String name;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

InitializingBean and DisposableBean Example

Let's create a service class where we will implement both the interfaces for post-init and pre-destroy methods.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 72/211 |

Page 73: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

EmployeeService.java

package com.journaldev.spring.service;

import org.springframework.beans.factory.DisposableBean;

import org.springframework.beans.factory.InitializingBean;

import com.journaldev.spring.bean.Employee;

public class EmployeeService implements InitializingBean, DisposableBean{

private Employee employee;

public Employee getEmployee() {

return employee;

}

public void setEmployee(Employee employee) {

this.employee = employee;

}

public EmployeeService(){

System.out.println("EmployeeService no-args constructor called");

}

@Override

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 73/211 |

Page 74: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

public void destroy() throws Exception {

System.out.println("EmployeeService Closing resources");

}

@Override

public void afterPropertiesSet() throws Exception {

System.out.println("EmployeeService initializing to dummy value");

if(employee.getName() == null){

employee.setName("Pankaj");

}

}

}

Service class with custom post-init and pre-destroy methods

Since we don't want our services to have direct spring framework dependency, let's create another form of Employee Service class

where we will have post-init and pre-destroy methods and we will configure them in the spring bean configuration file.

MyEmployeeService.java

package com.journaldev.spring.service;

import com.journaldev.spring.bean.Employee;

public class MyEmployeeService{

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 74/211 |

Page 75: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

private Employee employee;

public Employee getEmployee() {

return employee;

}

public void setEmployee(Employee employee) {

this.employee = employee;

}

public MyEmployeeService(){

System.out.println("MyEmployeeService no-args constructor called");

}

//pre-destroy method

public void destroy() throws Exception {

System.out.println("MyEmployeeService Closing resources");

}

//post-init method

public void init() throws Exception {

System.out.println("MyEmployeeService initializing to dummy value");

if(employee.getName() == null){

employee.setName("Pankaj");

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 75/211 |

Page 76: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

}

}

We will look into the spring bean configuration file in a bit. Before that let's create another service class that will use

@PostConstruct and @PreDestroy annotations.

@PostConstruct and @PreDestroy Example

Below is a simple class that will be configured as spring bean and for post-init and pre-destroy methods, we are using

@PostConstruct and @PreDestroy annotations.

MyService.java

package com.journaldev.spring.service;

import javax.annotation.PostConstruct;

import javax.annotation.PreDestroy;

public class MyService {

@PostConstruct

public void init(){

System.out.println("MyService init method called");

}

public MyService(){

System.out.println("MyService no-args constructor called");

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 76/211 |

Page 77: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

@PreDestroy

public void destory(){

System.out.println("MyService destroy method called");

}

}

Spring Bean Configuration File

Let's see how we will configure our beans in spring context file.

spring.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.xsd">

<!-- Not initializing employee name variable-->

<bean name="employee" class="com.journaldev.spring.bean.Employee" />

<bean name="employeeService" class="com.journaldev.spring.service.EmployeeService">

<property name="employee" ref="employee"></property>

</bean>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 77/211 |

Page 78: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<bean name="myEmployeeService" class="com.journaldev.spring.service.MyEmployeeService"

init-method="init" destroy-method="destroy">

<property name="employee" ref="employee"></property>

</bean>

<!-- initializing CommonAnnotationBeanPostProcessor is same as context:annotation-config -->

<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />

<bean name="myService" class="com.journaldev.spring.service.MyService" />

</beans>

Notice that I am not initializing employee name in it's bean definition. Since EmployeeService is using interfaces, we don't need any

special configuration here.

For MyEmployeeService bean, we are using init-method and destroy-method attributes to let spring framework know our custom

methods to execute.

MyService bean configuration doesn't have anything special, but as you can see that I am enabling annotation based configuration

for this.

Our application is ready, let's write a test program to see how different methods get executed.

Test Program

SpringMain.java

package com.journaldev.spring.main;

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 78/211 |

Page 79: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.journaldev.spring.service.EmployeeService;

import com.journaldev.spring.service.MyEmployeeService;

public class SpringMain {

public static void main(String[] args) {

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");

System.out.println("Spring Context initialized");

//MyEmployeeService service = ctx.getBean("myEmployeeService", MyEmployeeService.class);

EmployeeService service = ctx.getBean("employeeService", EmployeeService.class);

System.out.println("Bean retrieved from Spring Context");

System.out.println("Employee Name="+service.getEmployee().getName());

ctx.close();

System.out.println("Spring Context Closed");

}

}

When we run above test program, we get below output.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 79/211 |

Page 80: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Apr 01, 2014 10:50:50 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh

INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@c1b9b03: startup date [Tue Apr 01

22:50:50 PDT 2014]; root of context hierarchy

Apr 01, 2014 10:50:50 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

INFO: Loading XML bean definitions from class path resource [spring.xml]

EmployeeService no-args constructor called

EmployeeService initializing to dummy value

MyEmployeeService no-args constructor called

MyEmployeeService initializing to dummy value

MyService no-args constructor called

MyService init method called

Spring Context initialized

Bean retrieved from Spring Context

Employee Name=Pankaj

Apr 01, 2014 10:50:50 PM org.springframework.context.support.ClassPathXmlApplicationContext doClose

INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@c1b9b03: startup date [Tue Apr 01

22:50:50 PDT 2014]; root of context hierarchy

MyService destroy method called

MyEmployeeService Closing resources

EmployeeService Closing resources

Spring Context Closed

Important Points:

From the console output it's clear that Spring Context is first using no-args constructor to initialize the bean object and then calling

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 80/211 |

Page 81: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

the post-init method.

The order of bean initialization is same as it's defined in the spring bean configuration file.

The context is returned only when all the spring beans are initialized properly with post-init method executions.

Employee name is printed as ?Pankaj? because it was initialized in the post-init method.

When context is getting closed, beans are destroyed in the reverse order in which they were initialized i.e in LIFO

(Last-In-First-Out) order.

You can uncomment the code to get bean of type MyEmployeeService and confirm that output will be similar and follow all the

points mentioned above.

Spring Aware InterfacesSometimes we need Spring Framework objects in our beans to perform some operations, for example reading ServletConfig and

ServletContext parameters or to know the bean definitions loaded by the ApplicationContext. That's why spring framework provides

a bunch of *Aware interfaces that we can implement in our bean classes.

org.springframework.beans.factory.Aware is the root marker interface for all these Aware interfaces. All of the *Aware interfaces

are sub-interfaces of Aware and declare a single setter method to be implemented by the bean. Then spring context uses setter-based

dependency injection to inject the corresponding objects in the bean and make it available for our use.

Spring Aware interfaces are similar to servlet listeners with callback methods and implementing observer design pattern.

Some of the important Aware interfaces are:

- ApplicationContextAware ? to inject ApplicationContext object, example usage is to get the array of bean definition names.

- BeanFactoryAware ? to inject BeanFactory object, example usage is to check scope of a bean.

- BeanNameAware ? to know the bean name defined in the configuration file.

- ResourceLoaderAware ? to inject ResourceLoader object, example usage is to get the input stream for a file in the classpath.

- ServletContextAware ? to inject ServletContext object in MVC application, example usage is to read context parameters

and attributes.

- ServletConfigAware ? to inject ServletConfig object in MVC application, example usage is to get servlet config parameters.

Let's see these Aware interfaces usage in action by implementing few of them in a class that we will configure as spring bean.

MyAwareService.java

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 81/211 |

Page 82: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

package com.journaldev.spring.service;

import java.util.Arrays;

import org.springframework.beans.BeansException;

import org.springframework.beans.factory.BeanClassLoaderAware;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.BeanFactoryAware;

import org.springframework.beans.factory.BeanNameAware;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ApplicationContextAware;

import org.springframework.context.ApplicationEventPublisher;

import org.springframework.context.ApplicationEventPublisherAware;

import org.springframework.context.EnvironmentAware;

import org.springframework.context.ResourceLoaderAware;

import org.springframework.context.annotation.ImportAware;

import org.springframework.core.env.Environment;

import org.springframework.core.io.Resource;

import org.springframework.core.io.ResourceLoader;

import org.springframework.core.type.AnnotationMetadata;

public class MyAwareService implements ApplicationContextAware,

ApplicationEventPublisherAware, BeanClassLoaderAware, BeanFactoryAware,

BeanNameAware, EnvironmentAware, ImportAware, ResourceLoaderAware {

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 82/211 |

Page 83: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

@Override

public void setApplicationContext(ApplicationContext ctx)

throws BeansException {

System.out.println("setApplicationContext called");

System.out.println("setApplicationContext:: Bean Definition Names="

+ Arrays.toString(ctx.getBeanDefinitionNames()));

}

@Override

public void setBeanName(String beanName) {

System.out.println("setBeanName called");

System.out.println("setBeanName:: Bean Name defined in context="

+ beanName);

}

@Override

public void setBeanClassLoader(ClassLoader classLoader) {

System.out.println("setBeanClassLoader called");

System.out.println("setBeanClassLoader:: ClassLoader Name="

+ classLoader.getClass().getName());

}

@Override

public void setResourceLoader(ResourceLoader resourceLoader) {

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 83/211 |

Page 84: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

System.out.println("setResourceLoader called");

Resource resource = resourceLoader.getResource("classpath:spring.xml");

System.out.println("setResourceLoader:: Resource File Name="

+ resource.getFilename());

}

@Override

public void setImportMetadata(AnnotationMetadata annotationMetadata) {

System.out.println("setImportMetadata called");

}

@Override

public void setEnvironment(Environment env) {

System.out.println("setEnvironment called");

}

@Override

public void setBeanFactory(BeanFactory beanFactory) throws BeansException {

System.out.println("setBeanFactory called");

System.out.println("setBeanFactory:: employee bean singleton="

+ beanFactory.isSingleton("employee"));

}

@Override

public void setApplicationEventPublisher(

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 84/211 |

Page 85: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

ApplicationEventPublisher applicationEventPublisher) {

System.out.println("setApplicationEventPublisher called");

}

}

Spring Bean Configuration File

Very simple spring bean configuration file.

spring-aware.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.xsd">

<bean name="employee" class="com.journaldev.spring.bean.Employee" />

<bean name="myAwareService" class="com.journaldev.spring.service.MyAwareService" />

</beans>

Spring *Aware Test Program

SpringAwareMain.java

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 85/211 |

Page 86: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

package com.journaldev.spring.main;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.journaldev.spring.service.MyAwareService;

public class SpringAwareMain {

public static void main(String[] args) {

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring-aware.xml");

ctx.getBean("myAwareService", MyAwareService.class);

ctx.close();

}

}

Now when we execute above class, we get following output.

Apr 01, 2014 11:27:05 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh

INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@60a2f435: startup date [Tue Apr 01

23:27:05 PDT 2014]; root of context hierarchy

Apr 01, 2014 11:27:05 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

INFO: Loading XML bean definitions from class path resource [spring-aware.xml]

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 86/211 |

Page 87: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

setBeanName called

setBeanName:: Bean Name defined in context=myAwareService

setBeanClassLoader called

setBeanClassLoader:: ClassLoader Name=sun.misc.Launcher$AppClassLoader

setBeanFactory called

setBeanFactory:: employee bean singleton=true

setEnvironment called

setResourceLoader called

setResourceLoader:: Resource File Name=spring.xml

setApplicationEventPublisher called

setApplicationContext called

setApplicationContext:: Bean Definition Names=[employee, myAwareService]

Apr 01, 2014 11:27:05 PM org.springframework.context.support.ClassPathXmlApplicationContext doClose

INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@60a2f435: startup date [Tue Apr 01

23:27:05 PDT 2014]; root of context hierarchy

Console output of the test program is simple to understand, I won't go into much detail about that.

 

 Explain Bean lifecycle in Spring framework?

Following is sequence of a bean lifecycle in Spring:

Instantiate- First the spring container finds the bean's definition from the XML file and instantiates the bean..

Populate properties- Using the dependency injection, spring populates all of the properties as specified in the bean definition..

Set Bean Name- If the bean implements BeanNameAware interface, spring passes the bean's id to setBeanName() method.

Set Bean factory- If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.

Pre Initialization- Also called postprocess of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls

postProcesserBeforeInitialization() method.

Initialize beans- If the bean implements IntializingBean,its afterPropertySet() method is called. If the bean has init method

declaration, the specified initialization method is called.

Post Initialization- If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods

will be called.

Ready to use- Now the bean is ready to use by the application.

Destroy- If the bean implements DisposableBean , it will call the destroy() method .

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 87/211 |

Page 88: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

What are inner beans in Spring?

- A <bean/> element inside the <property/> or <constructor-arg/> elements defines a so-called inner bean. An inner bean

definition does not require a defined id or name; the container ignores these values. It also ignores the scope flag. Inner beans

are always anonymous and they are always scoped as prototypes.

How can you inject Java Collection in Spring?

- Spring offers four types of collection configuration elements which are as follows:

<list>: This helps in wiring i.e. injecting a list of values, allowing duplicates.

<set>: This helps in wiring a set of values but without any duplicates.

<map>: This can be used to inject a collection of name-value pairs where name and value can be of any type.

<props>: This can be used to inject a collection of name-value pairs where the name and value are both Strings.

What is Bean wiring and @Autowired annotation?

- The process of injection spring bean dependencies while initializing it called Spring Bean Wiring.

Usually it's best practice to do the explicit wiring of all the bean dependencies, but spring framework also supports autowiring. We

can use @Autowired annotation with fields or methods for autowiring byType. For this annotation to work, we also need to enable

annotation based configuration in spring bean configuration file. This can be done by context:annotation-config - For more details about @Autowired annotation, please read Spring Autowire Example.]

 

What is bean auto wiring?

- The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to

automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory

without using <constructor-arg> and <property> elements.

What are different Modes of auto wiring?

- The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for

dependency injection:

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

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 88/211 |

Page 89: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

What are the limitations with autowiring?

Limitations of autowiring are:

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

Can you inject null and empty string values in Spring?Example On Spring Autowiring byName

In this case, spring framework attempts to find out a bean in the configuration file, whose id is matching with the property name to

be wired.  If a bean found with id as property name then that class object will be injected into that property by calling setter

injection.  If no id is found then that property remains un-wired, but never throws any exception.

Example On Autowiring byName

public class MyBean

{

private DemoBean db;

public void setDb(DemoBean db)

{

this.db=db;

}

}

In the xml file

<beans>

<bean id="id1" class="MyBean" autowire="byName" />

<bean id="db" class="DemoBean" />

</beans>

Explanation:

See line number 3 in MyBean, our class depends on DemoBean class object right,  now see in the xml file line number 2 we have

given autowire=?byName?, means when ever spring container notice autowire=?byName? then it will verifies whether the id in xml

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 89/211 |

Page 90: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

file is matching with the property name in the MyBean or not, if yes it will wired  automatically else unwired

Am giving one figure to make you understand better :-)

Complete Example

Files required?

- java

- java

- java

- xml

Book.java

package technicalstack;

public class Book {

private String bookname;

private int bookprice;

public String getBookname() {

return bookname;

}

public void setBookname(String bookname) {

this.bookname = bookname;

}

public int getBookprice() {

return bookprice;

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 90/211 |

Page 91: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

public void setBookprice(int bookprice) {

this.bookprice = bookprice;

}

}

Categories.java

package technicalstack;

public class Categories {

private String name;

private Book bk;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Book getBk() {

return bk;

}

public void setBk(Book bk) {

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 91/211 |

Page 92: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

this.bk = bk;

}

public void show()

{

System.out.println("Categories name :"+name);

System.out.println("Book name :"+bk.getBookname()+" and Book Price :"+bk.getBookprice());

}

}

ClientLogic.java

package technicalstack;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.ClassPathResource;

import org.springframework.core.io.Resource;

public class ClientLogic {

public static void main(String[] args)

{

Resource res = new ClassPathResource("spconfig.xml");

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 92/211 |

Page 93: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

BeanFactory factory = new XmlBeanFactory(res);

Object o = factory.getBean("id1");

Categories wb = (Categories)o;

wb.show();

}

}

spconfig.xml

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"

"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>

<bean id="id1" class="technicalstack.Categories" autowire="byName">

<property name="name" value="General Books" />

</bean>

<bean id="bk" class="technicalstack.Book">

<property name="bookname" value="The Kids" />

<property name="bookprice" value="300" />

</bean>

</beans>

Notes: We called id1 from ClientLogic.java [line number 15], and in spconfig.xml we have written autowire=byName, so first it will

checks for the class with id name bk [as we have written private Book bk in Categories.java ] and inserts bk class [ jaa4s.Book ]

properties into that object and then injects value ?General Books? into name property of Categories class.

Finally in ClientLogic.java we used to type cast to get our output.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 93/211 |

Page 94: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Output

Example On Spring Autowiring byType

Let us see an application on Spring Autowiring with byType, let me clear this confusion about byType,byName?

Avoid byType ? byName confusion

In this case, spring framework attempts to find out a bean in the configuration file, whose id is matching with the property type to be

wired.  If a bean found with class as property type then that class object will be injected into that property by calling setter injection. 

If no class found then that property remains un-wired, but never throws any exception just like before.

Example On Spring Autowiring byType

Files required?

- java

- java

- java

- xml

Book.java

package technicalstack;

public class Book {

private String bookname;

private int bookprice;

public String getBookname() {

return bookname;

}

public void setBookname(String bookname) {

this.bookname = bookname;

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 94/211 |

Page 95: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

}

public int getBookprice() {

return bookprice;

}

public void setBookprice(int bookprice) {

this.bookprice = bookprice;

}

}

Categories.java

package technicalstack;

public class Categories {

private String name;

private Book bk;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 95/211 |

Page 96: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

public Book getBk() {

return bk;

}

public void setBk(Book bk) {

this.bk = bk;

}

public void show()

{

System.out.println("Categories name :"+name);

System.out.println("Book name :"+bk.getBookname()+" and Book Price :"+bk.getBookprice());

}

}

ClientLogic.java

package technicalstack;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.ClassPathResource;

import org.springframework.core.io.Resource;

public class ClientLogic {

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 96/211 |

Page 97: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

public static void main(String[] args)

{

Resource res = new ClassPathResource("spconfig.xml");

BeanFactory factory = new XmlBeanFactory(res);

Object o = factory.getBean("id1");

Categories wb = (Categories)o;

wb.show();

}

}

spconfig.xml

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"

"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>

<bean id="id1" class="technicalstack.Categories" autowire="byType">

<property name="name" value="General Books" />

</bean>

<bean id="SomeThing" class="technicalstack.Book">

<property name="bookname" value="The Kids" />

<property name="bookprice" value="300" />

</bean>

</beans>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 97/211 |

Page 98: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Notes: We called id1 from ClientLogic.java [line number 15], and in spconfig.xml we have written autowire=byType, so first spring

container will checks for the bean with class attribute Book [as autowire=byType and we have written private Book bk in

Categories.java  ] and then inserts Book class properties into Book class object [ jav4s.Book ] and gives this book class object to

Categories then injects value ?General Books? into name property of Categories class.  [ read slowly 2 or 3 times]

Finally in ClientLogic.java we used to type cast to get our output.

Example On Spring Autowiring by Constructor

Actually Spring Autowiring by constructor is similar to spring autowiring byType [ internally it will considers as byType only ]  but

with little difference, in byType we used setter injection here we have to use constructor injection :-)  nothing more than that.

Friends am using same application to show the difference between byName, byType, constructor, autodetect to avoid confusions [

Out put is same for all these 4 applications ;) ]

Example On Spring Autowiring Constructor

Files required?

- java

- java

- java

- xml

Book.java

package technicalstack;

public class Book {

private String bookname;

private int bookprice;

public String getBookname() {

return bookname;

}

public void setBookname(String bookname) {

this.bookname = bookname;

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 98/211 |

Page 99: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

public int getBookprice() {

return bookprice;

}

public void setBookprice(int bookprice) {

this.bookprice = bookprice;

}

}

Categories.java

package technicalstack;

public class Categories {

private String name;

private Book bk;

public Categories(Book bk)

{

this.bk=bk;

}

public String getName() {

return name;

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 99/211 |

Page 100: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

public void setName(String name) {

this.name = name;

}

public void show()

{

System.out.println("Categories name :"+name);

System.out.println("Book name :"+bk.getBookname()+" and Book Price :"+bk.getBookprice());

}

}

ClientLogic.java

package technicalstack;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.ClassPathResource;

import org.springframework.core.io.Resource;

public class ClientLogic {

public static void main(String[] args)

{

Resource res = new ClassPathResource("spconfig.xml");

BeanFactory factory = new XmlBeanFactory(res);

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 100/211 |

Page 101: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Object o = factory.getBean("id1");

Categories wb = (Categories)o;

wb.show();

}

}

spconfig.xml

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"

"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>

<bean id="id1" class="technicalstack.Categories" autowire="constructor">

<property name="name" value="General Books" />

</bean>

<bean id="SomeThing" class="technicalstack.Book">

<property name="bookname" value="The Kids" />

<property name="bookprice" value="300" />

</bean>

</beans>

Notes:  Friends am not explaining this program, as i told you earlier Spring Autowiring constructor is similar to Spring Autowiring

byType but here we use constructor injection, please refer byType if you still have any doubts.

Output

Example On Spring Autowiring by Autodetect

Let us see the example on spring Autowiring with autowire as autodetect.  Actually spring autowire=?autodetect? frist will works as

Spring Autowiring constructor if not then works as Spring Autowiring byType, byType means setter injection right hope you

remember :-)  well will see the example..

Example On Spring Autowiring autodetect

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 101/211 |

Page 102: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Files required?

- java

- java

- java

- xml

Book.java

package technicalstack;

public class Book {

private String bookname;

private int bookprice;

public String getBookname() {

return bookname;

}

public void setBookname(String bookname) {

this.bookname = bookname;

}

public int getBookprice() {

return bookprice;

}

public void setBookprice(int bookprice) {

this.bookprice = bookprice;

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 102/211 |

Page 103: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

}

Categories.java

package technicalstack;

public class Categories {

private String name;

private Book bk;

public Categories(Book bk)

{

this.bk=bk;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public void show()

{

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 103/211 |

Page 104: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

System.out.println("Categories name :"+name);

System.out.println("Book name :"+bk.getBookname()+" and Book Price :"+bk.getBookprice());

}

}

ClientLogic.java

package technicalstack;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.ClassPathResource;

import org.springframework.core.io.Resource;

public class ClientLogic {

public static void main(String[] args)

{

Resource res = new ClassPathResource("spconfig.xml");

BeanFactory factory = new XmlBeanFactory(res);

Object o = factory.getBean("id1");

Categories wb = (Categories)o;

wb.show();

}

}

spconfig.xml

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 104/211 |

Page 105: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"

"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>

<bean id="id1" class="technicalstack.Categories" autowire="autodetect">

<property name="name" value="General Books" />

</bean>

<bean id="SomeThing" class="technicalstack.Book">

<property name="bookname" value="The Kids" />

<property name="bookprice" value="300" />

</bean>

</beans>

What is Annotation-based container configuration?

- An alternative to XML setups is provided by annotation-based configuration which relies on the bytecode metadata for

wiring up components instead of angle-bracket declarations. Instead of using XML to describe a bean wiring, the developer

moves the configuration into the component class itself by using annotations on the relevant class, method, or field

declaration.

How do you turn on annotation wiring?

- 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 by configuring <context:annotation-config/>.

What does @Required annotation mean?

- This annotation simply indicates that the affected bean property must be populated at configuration time, through an explicit

property value in a bean definition or through autowiring. The container throws BeanInitializationException if the affected

bean property has not been populated.

Spring @Required Annotation and RequiredAnnotationBeanPostProcessor Example

In a production-scale application, there may be hundreds or thousands of beans declared in the IoC container, and the dependencies

between them are often very complicated. One of the shortcomings of setter injection is that it's very hard for you to check if all

required properties have been set or not. To overcome this problem, you can set ?dependency-check? attribute of <bean> and set one

of four attributes i.e. none, simple, objects or all (none is default option). Here this dependency checking feature can only check if

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 105/211 |

Page 106: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

the properties have been set for that bean or not; but it can't check if their value is not null.

In real life application, you will not be interested in checking all the bean properties configured in your context files. Rather you

would like to check if particular set of properties have been set or not in some specific beans only. Spring's dependency checking

feature using ?dependency-check? attribute, will not able to help you in this case. So solve this problem, you can use @Required

annotation.

How to use @Required annotation

Use the @Required annotation over setter method of bean property in class file as below:

public class EmployeeFactoryBean extends AbstractFactoryBean<Object>

{

private String designation;

public String getDesignation() {

return designation;

}

@Required

public void setDesignation(String designation) {

this.designation = designation;

}

//more code here

}

RequiredAnnotationBeanPostProcessor is a spring bean post processor that checks if all the bean properties with the @Required

annotation have been set. To enable this bean post processor for property checking, you must register it in the Spring IoC container.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 106/211 |

Page 107: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" />

Note that this processor can check only if the properties have been set, but can't check if their value is not null.

 

If any properties with @Required have not been set, a BeanInitializationException will be thrown by this bean post processor. For

example, if I will create an instance of EmployeeFactoryBean class without passing property value for designation, then I will get

this error.

applicationContext.xml

<bean id="manager"  class="com.technicalstack.demo.factory.EmployeeFactoryBean">

<!-- <property name="designation" value="Manager" /> -->

</bean>

<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" />

Read More : Spring FactoryBean Example

Error Message

Caused by: org.springframework.beans.factory.BeanInitializationException: Property 'designation' is required for bean

'manager'

at

org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor.postProcessPropertyValues(RequiredAnnotat

ionBeanPostProcessor.java:156)

at

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFac

tory.java:1202)

at

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFa

ctory.java:537)

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 107/211 |

Page 108: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

... 11 more

To correct this problem, pass the designation value by un-commenting the line in applicationContext.xml file.

In this way, you can use @Required annotation and RequiredAnnotationBeanPostProcessor class to verify that on context

initialization, all the required bean properties have been set properly.

What does @Autowired annotation mean?

The @Autowired annotation provides more fine-grained control over where and how autowiring should be accomplished. The

@Autowired annotation can be used to autowire bean on the setter method just like @Required annotation, constructor, a property

or methods with arbitrary names and/or multiple arguments.

E.g. You can use @Autowired annotation on setter methods to get rid of the <property> element in XML configuration file. When

Spring finds an @Autowired annotation used with setter methods, it tries to perform byType autowiring on the method.

You can apply @Autowired to constructors as well. A constructor @Autowired annotation indicates that the constructor should be

autowired when creating the bean, even if no <constructor-arg> elements are used while configuring the bean in XML file.

public class TextEditor {

private SpellChecker spellChecker;

@Autowired

public TextEditor(SpellChecker spellChecker){

System.out.println("Inside TextEditor constructor." );

this.spellChecker = spellChecker;

}

public void spellCheck(){

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 108/211 |

Page 109: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

spellChecker.checkSpelling();

}

}

And it's configuration without constructor arguments.

<beans>

<context:annotation-config/>

<!-- Definition for textEditor bean without constructor-arg  -->

<bean id="textEditor" class="com.technicalstack.TextEditor">

</bean>

<!-- Definition for spellChecker bean -->

<bean id="spellChecker" class="com.technicalstack.SpellChecker">

</bean>

</beans>

Explain @Qualifier annotation with example?

@Qualifier means, which bean is qualify to autowired on a field. The qualifier annotation helps disambiguate beanreferences when Spring would otherwise not be able to do so.

See below example, it will autowired a ?person? bean into customer's person property.

public class Customer

{

@Autowired

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 109/211 |

Page 110: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

private Person person;

}

And we have two bean definitions for Person class.

<bean id="customer" class="com.technicalstack.common.Customer" />

<bean id="personA" class="com.technicalstack.common.Person" >

<property name="name" value="lokesh" />

</bean>

<bean id="personB" class="com.technicalstack.common.Person" >

<property name="name" value="alex" />

</bean>

Will Spring know which person bean should autowired? NO. When you run above example, it hits below exception :

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:

No unique bean of type [com.technicalstack.common.Person] is defined:

expected single matching bean but found 2: [personA, personB]

To fix above problem, you need @Quanlifier to tell Spring about which bean should autowired.

public class Customer

{

@Autowired

@Qualifier("personA")

private Person person;

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 110/211 |

Page 111: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

}

How to use Spring @Component, @Repository, @Service and @Controller Annotations, @RequestMapping?

In spring autowiring concepts, we learned about @Autowired annotation that it handles only wiring. You still have to define the

beans themselves so the container is aware of them and can inject them for you. But with @Component, @Repository, @Service

and @Controller annotations in place and after enabling automatic component scanning, spring will automatically import the beans

into the container so you don't have to define them explicitly with XML. These annotations are called Stereotype annotations as

well.

Before jumping to example use of these annotations, let's learn quick facts about these annotations which will help you in making a

better decision about when to use which annotation.

@Component, @Repository, @Service and @Controller annotations

1) The @Component annotation marks a java class as a bean so the component-scanning mechanism of spring can pick it up and

pull it into the application context. To use this annotation, apply it over class as below:

@Component

public class EmployeeDAOImpl implements EmployeeDAO {

...

}

2) Although above use of @Component is good enough but you can use more suitable annotation that provides additional benefits

specifically for DAOs i.e. @Repository annotation. The @Repository annotation is a specialization of the @Component annotation

with similar use and functionality. In addition to importing the DAOs into the DI container, it also makes the unchecked exceptions

(thrown from DAO methods) eligible for translation into Spring DataAccessException.

3) The @Service annotation is also a specialization of the component annotation. It doesn't currently provide any additional behavior

over the @Component annotation, but it's a good idea to use @Service over @Component in service-layer classes because it

specifies intent better. Additionally, tool support and additional behavior might rely on it in the future.

4) @Controller annotation marks a class as a Spring Web MVC controller. It too is a @Component specialization, so beans marked

with it are automatically imported into the DI container. When you add the @Controller annotation to a class, you can use another

annotation i.e. @RequestMapping; to map URLs to instance methods of a class.

In real life, you will face very rare situations where you will need to use @Component annotation. Most of the time, you will using

@Repository, @Service and @Controller annotations. @Component should be used when your class does not fall into either of

three categories i.e. controller, manager and dao.

If you want to define name of the bean with which they will be registered in DI container, you can pass the name in annotation itself

e.g. @Service (?employeeManager?).

How to enable component scanning

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 111/211 |

Page 112: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Above four annotation will be scanned and configured only when they are scanned by DI container of spring framework. To enable

this scanning, you will need to use ?context:component-scan? tag in your applicationContext.xml file. e.g.

<context:component-scan base-package="com.technicalstack.demo.service" />

<context:component-scan base-package="com.technicalstack.demo.dao" />

<context:component-scan base-package="com.technicalstack.demo.controller" />

The context:component-scan element requires a base-package attribute, which, as its name suggests, specifies a starting point

for a recursive component search. You may not want to give your top package for scanning to spring, so you should declare three

component-scan elements, each with a base-package attribute pointing to a different package.

When component-scan is declared, you no longer need to declare context:annotation-config, because autowiring is implicitly

enabled when component scanning is enabled.

How to use @Component, @Repository, @Service and @Controller Annotations

As I already said that you use @Repository, @Service and @Controller annotations over DAO, manager and controller classes. But

in real life, at DAO and manager layer we often have separate classes and interfaces. Interface for defining the contract, and classes

for defining the implementations of contracts. Where to use these annotations? Let's find out.

Always use these annotations over concrete classes; not over interfaces.

Once you have these stereotype annotations on beans, you can directly use bean references defined inside concrete classes. Note the

references are of type interfaces. Spring DI container is smart enough to inject the correct instance in this case.

EmployeeDAO.java and EmployeeDAOImpl.java

public interface EmployeeDAO

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 112/211 |

Page 113: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

{

public EmployeeDTO createNewEmployee();

}

@Repository ("employeeDao")

public class EmployeeDAOImpl implements EmployeeDAO

{

public EmployeeDTO createNewEmployee()

{

EmployeeDTO e = new EmployeeDTO();

e.setId(1);

e.setFirstName("Lokesh");

e.setLastName("Gupta");

return e;

}

}

EmployeeManager.java and EmployeeManagerImpl.java

public interface EmployeeManager

{

public EmployeeDTO createNewEmployee();

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 113/211 |

Page 114: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

@Service ("employeeManager")

public class EmployeeManagerImpl implements EmployeeManager

{

@Autowired

EmployeeDAO dao;

public EmployeeDTO createNewEmployee()

{

return dao.createNewEmployee();

}

}

EmployeeController.java

@Controller ("employeeController")

public class EmployeeController

{

@Autowired

EmployeeManager manager;

public EmployeeDTO createNewEmployee()

{

return manager.createNewEmployee();

}

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 114/211 |

Page 115: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

EmployeeDTO.java

public class EmployeeDTO {

private Integer id;

private String firstName;

private String lastName;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getFirstName() {

return firstName;

}

public void setFirstName(String firstName) {

this.firstName = firstName;

}

public String getLastName() {

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 115/211 |

Page 116: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

return lastName;

}

public void setLastName(String lastName) {

this.lastName = lastName;

}

@Override

public String toString() {

return "Employee [id=" + id + ", firstName=" + firstName

+ ", lastName=" + lastName + "]";

}

}

Let's test the above configuration and annotations:

TestSpringContext.java

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.technicalstack.demo.service.EmployeeManager;

public class TestSpringContext

{

public static void main(String[] args)

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 116/211 |

Page 117: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

{

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

//EmployeeManager manager = (EmployeeManager) context.getBean(EmployeeManager.class);

//OR this will also work

EmployeeController controller = (EmployeeController) context.getBean("employeeController");

System.out.println(controller.createNewEmployee());

}

}

Output:

Jan 22, 2015 6:17:57 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh

INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1b2b2f7f:

startup date [Thu Jan 22 18:17:57 IST 2015]; root of context hierarchy

Jan 22, 2015 6:17:57 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

INFO: Loading XML bean definitions from class path resource [applicationContext.xml]

Employee [id=1, firstName=Lokesh, lastName=Gupta]

 

 Bean Lifecycle and Callbacks

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 117/211 |

Page 118: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

- The Spring Framework provide several call back methods to created a bean and some method to be destroy the bean in the

Spring IoC Container.

- The Spring Framework provides several marker interfaces to change the behavior of your bean in the container; they

include InitializingBean and DisposableBean. Implementing these interfaces will result in the container calling

afterPropertiesSet() for the former and destroy() for the latter to allow the bean to perform certain actions upon initialization

and destruction.

- The life cycle of a Spring bean is easy to understand. When a bean is instantiated, it may be required to perform some

initialization to get it into a usable state. Similarly, when the bean is no longer required and is removed from the container,

some cleanup may be required.

- Beans can be notified after creation and all properties are set, and before they are destroyed and removed from the bean

container. This involves specifying the callback method to be invoked by the container. This is done in XML by specifying

attributes init-method="myinit", for the initialization callback, and destroy-method="mydestroy", for the destroy callback.

"myinit" and "cleanUp" are names of instance methods in the bean class.

Initialization callbacks:

- Implementing the org.springframework.beans.factory.InitializingBean interface allows a bean to perform initialization work

after all necessary properties on the bean are set by the container. The InitializingBean interface specifies exactly one

method:

org.springframework.beans.factory.InitializingBean interface  provide Initialization callbacks method as given below..

void afterPropertiesSet() throws Exception

void afterPropertiesSet() throws Exception

Now we can implements above interface and do some initialization functionality with in this method. As below..

public class Triangle implements InitializingBean

{

@Override

public void afterPropertiesSet() throws Exception

{

//To do some initialization works here

System.out.println("InitializingBean init method is called for Triangle");

}

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 118/211 |

Page 119: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

public class Triangle implements InitializingBean

{

@Override

public void afterPropertiesSet() throws Exception

{

//To do some initialization works here

System.out.println("InitializingBean init method is called for Triangle");

}

}

Generally, the use of the InitializingBean interface can be avoided (and is discouraged since it unnecessarily couples the code to

Spring). A bean definition provides support for a generic initialization method to be specified. In the case of XML-based

configuration metadata, this is done using the 'init-method' attribute. For example, the following definition:

In the case of XML-based configuration metadata, we can use the init-method attribute to specify the name of the method that has a

void no-argument signature. For example:

Now following has myInit method in class.

public class Triangle

{

public void myInit()

{

//To do some initialization works here

System.out.println("My init method is called for Triangle");

}

}

public class Triangle

{

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 119/211 |

Page 120: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

public void myInit()

{

//To do some initialization works here

System.out.println("My init method is called for Triangle");

}

}

Now using Java annotations can also be used to declare life-cycle callbacks.

public class Triangle

{

//init callback

@PostConstruct

public void myInit()

{

//To do some initialization works here

System.out.println("My init method is called for Triangle");

}

}

public class Triangle

{

//init callback

@PostConstruct

public void myInit()

{

//To do some initialization works here

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 120/211 |

Page 121: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

System.out.println("My init method is called for Triangle");

}

}

Destruction callbacks:

Implementing the org.springframework.beans.factory.DisposableBean interface allows a bean to get a callback when the container

containing it is destroyed. The DisposableBean interface specifies one method:

void destroy() throws Exception

Now we can implements above interface and do some Destruction functionality with in this method. As below..

public class Triangle implements DisposableBean

{

@Override

public void destroy() throws Exception

{

//To do some Destruction works here

System.out.println("DisposableBean destroy method is called for Triangle");

}

}

public class Triangle implements DisposableBean

{

@Override

public void destroy() throws Exception

{

//To do some Destruction works here

System.out.println("DisposableBean destroy method is called for Triangle");

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 121/211 |

Page 122: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

}

Generally, the use of the DisposableBean marker interface can be avoided (and is discouraged since it unnecessarily couples the

code to Spring). A bean definition provides support for a generic destroy method to be specified. When using XML-based

configuration metadata this is done via the 'destroy-method' attribute on the . For example, the following definition:

In the case of XML-based configuration metadata, we can use the destroy-method attribute to specify the name of the method that

has a void no-argument signature. For example:

Now following has cleanUp method in class.

public class Triangle

{

public void cleanUp()

{

//To do some Destruction works here

System.out.println("cleanUp method is called for Triangle");

}

}

public class Triangle

{

public void cleanUp()

{

//To do some Destruction works here

System.out.println("cleanUp method is called for Triangle");

}

}

Now using Java annotations can also be used to declare life-cycle callbacks.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 122/211 |

Page 123: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

public class Triangle

{

//destroy callback

@PreDestroy

public void myInit()

{

//To do some Destruction works here

System.out.println("cleanUp method is called for Triangle");

}

}

public class Triangle

{

//destroy callback

@PreDestroy

public void myInit()

{

//To do some Destruction works here

System.out.println("cleanUp method is called for Triangle");

}

}

If you are using Spring's IoC container in a non-web application environment; for example, in a rich client desktop environment; you

register a shutdown hook with the JVM. Doing so ensures a graceful shutdown and calls the relevant destroy methods on your

singleton beans so that all resources are released. It is recommended that you do not use the InitializingBean or DisposableBean

callbacks, because XML configuration gives much flexibility in terms of naming your method.

Example:

Triangle.java

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 123/211 |

Page 124: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

package com.dineshonjava.sdnext.callbackLifecycle.tutorial;

import org.springframework.beans.factory.DisposableBean;

import org.springframework.beans.factory.InitializingBean;

public class Triangle implements InitializingBean, DisposableBean

{

private Point pointA;

private Point pointB;

private Point pointC;

/**

* @param pointA the pointA to set

*/

public void setPointA(Point pointA) {

this.pointA = pointA;

}

/**

* @param pointB the pointB to set

*/

public void setPointB(Point pointB) {

this.pointB = pointB;

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 124/211 |

Page 125: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

/**

* @param pointC the pointC to set

*/

public void setPointC(Point pointC) {

this.pointC = pointC;

}

public void draw()

{

System.out.println("PointA is ("+pointA.getX()+", "+pointA.getY()+")");

System.out.println("PointB is ("+pointB.getX()+", "+pointB.getY()+")");

System.out.println("PointC is ("+pointC.getX()+", "+pointC.getY()+")");

}

@Override

public void afterPropertiesSet() throws Exception

{

System.out.println("InitializingBean init method is called for Triangle");

}

@Override

public void destroy() throws Exception

{

System.out.println("DisposableBean destroy method is called for Triangle");

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 125/211 |

Page 126: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

public void myInit()

{

System.out.println("My init method is called for Triangle");

}

public void cleanUp()

{

System.out.println("cleanUp method is called for Triangle");

}

}

Point.java

package com.dineshonjava.sdnext.callbackLifecycle.tutorial;

public class Point

{

private int x;

private int y;

/**

* @return the x

*/

public int getX() {

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 126/211 |

Page 127: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

return x;

}

/**

* @param x the x to set

*/

public void setX(int x) {

this.x = x;

}

/**

* @return the y

*/

public int getY() {

return y;

}

/**

* @param y the y to set

*/

public void setY(int y) {

this.y = y;

}

}

package com.dineshonjava.sdnext.callbackLifecycle.tutorial;

public class Point

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 127/211 |

Page 128: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

{

private int x;

private int y;

/**

* @return the x

*/

public int getX() {

return x;

}

/**

* @param x the x to set

*/

public void setX(int x) {

this.x = x;

}

/**

* @return the y

*/

public int getY() {

return y;

}

/**

* @param y the y to set

*/

public void setY(int y) {

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 128/211 |

Page 129: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

this.y = y;

}

}

Following is the configuration file Spring.xml required for init and destroy methods.

Spring.xml

<bean id=triangle class=com.dineshonjava.sdnext.callbackLifecycle.tutorial.Triangle init-method="myInit"

destroy-method="cleanUp" autowire="byName">

</bean>

<bean id=pointA class=com.dineshonjava.sdnext.callbackLifecycle.tutorial.Point>

<property name="x" value="0"></property>

<property name="y" value="0"></property>

</bean>

<bean id=pointB class=com.dineshonjava.sdnext.callbackLifecycle.tutorial.Point>

<property name="x" value="-20"></property>

<property name="y" value="0"></property>

</bean>

<bean id=pointC class=com.dineshonjava.sdnext.callbackLifecycle.tutorial.Point>

<property name="x" value="20"></property>

<property name="y" value="0"></property>

</bean>

</beans>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 129/211 |

Page 130: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Once you are done with creating source and bean configuration files, let us run the following application. If everything is fine with

your application, this will print the following message:

package com.dineshonjava.sdnext.callbackLifecycle.tutorial;

import org.springframework.context.support.AbstractApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

/**

* @author Dinesh Rajput

*

*/

public class DrawingApp

{

/**

* @param args

*/

public static void main(String[] args)

{

AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

context.registerShutdownHook();

Triangle triangle = (Triangle) context.getBean("triangle");

triangle.draw();

}

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 130/211 |

Page 131: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

package com.dineshonjava.sdnext.callbackLifecycle.tutorial;

import org.springframework.context.support.AbstractApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

/**

* @author Dinesh Rajput

*

*/

public class DrawingApp

{

/**

* @param args

*/

public static void main(String[] args)

{

AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

context.registerShutdownHook();

Triangle triangle = (Triangle) context.getBean("triangle");

triangle.draw();

}

}

Output:

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 131/211 |

Page 132: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Jul 1, 2012 2:48:33 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh

INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@ab50cd: startup date [Sun Jul 01

14:48:33 IST 2012]; root of context hierarchy

Jul 1, 2012 2:48:33 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

INFO: Loading XML bean definitions from class path resource [spring.xml]

Jul 1, 2012 2:48:33 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons

INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1543c88: defining

beans [triangle,pointA,pointB,pointC]; root of factory hierarchy

InitializingBean init method is called for Triangle

My init method is called for Triangle

PointA is (0, 0)

PointB is (-20, 0)

PointC is (20, 0)

Jul 1, 2012 2:48:33 PM org.springframework.context.support.AbstractApplicationContext doClose

INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@ab50cd: startup date [Sun Jul 01 14:48:33

IST 2012]; root of context hierarchy

DisposableBean destroy method is called for Triangle

cleanUp method is called for Triangle

Default initialization and destroy methods: If you have too many beans having initialization and or destroy methods with the same

name, you don't need to declare init-method and destroy-method on each individual bean. Instead framework provides the flexibility

to configure such situation using default-init-method and default-destroy-method attributes on the <beans> element as follows:

spring.xml

<bean id=triangle class=com.dineshonjava.sdnext.callbackLifecycle.tutorial.Triangle autowire="byName">

</bean>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 132/211 |

Page 133: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<bean id=pointA class=com.dineshonjava.sdnext.callbackLifecycle.tutorial.Point>

<property name="x" value="0"></property>

<property name="y" value="0"></property>

</bean>

<bean id=pointB class=com.dineshonjava.sdnext.callbackLifecycle.tutorial.Point>

<property name="x" value="-20"></property>

<property name="y" value="0"></property>

</bean>

<bean id=pointC class=com.dineshonjava.sdnext.callbackLifecycle.tutorial.Point>

<property name="x" value="20"></property>

<property name="y" value="0"></property>

</bean>

</beans>

Now again run the application with above the configuration file we will get the following output:

Output:

Jul 1, 2012 2:58:00 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh

INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@ab50cd: startup date [Sun Jul 01

14:58:00 IST 2012]; root of context hierarchy

Jul 1, 2012 2:58:00 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

INFO: Loading XML bean definitions from class path resource [spring.xml]

Jul 1, 2012 2:58:01 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons

INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1543c88: defining

beans [triangle,pointA,pointB,pointC]; root of factory hierarchy

InitializingBean init method is called for Triangle

My init method is called for Triangle

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 133/211 |

Page 134: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

PointA is (0, 0)

PointB is (-20, 0)

PointC is (20, 0)

DisposableBean destroy method is called for Triangle

cleanUp method is called for Triangle

4 ways to schedule tasks in Spring 3 : @Scheduled example

In previous post, we learned about 2 ways to use timer tasks in spring 3 framework. Spring provides excellent support for scheduling

jobs based on cron expression also. This scheduling is possible with use of @Scheduled annotation. According to spring

documentation:

Spring 3.0 also adds annotation support for both task scheduling and asynchronous method execution. The @Scheduled annotation

can be added to a method along with trigger metadata.

In this post, I will show the means to use this feature in 4 different ways.

Sections in this post:

Explaining @Scheduled annotation

Task scheduling using fixed delay attribute in @Scheduled annotation

Task scheduling using cron expression in @Scheduled annotation

Task scheduling using cron expression from properties file and @Scheduled annotation

Task scheduling using cron expression configured in context configuration

Sourcecode download link

Explaining @Scheduled annotation

This annotation is used for task scheduling. The trigger information needs to be provided along with this annotation. You can use the

properties fixedDelay/fixedRate/cron to provide the triggering information.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 134/211 |

Page 135: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

fixedRate makes Spring run the task on periodic intervals even if the last invocation may be still running.

fixedDelay specifically controls the next execution time when the last execution finishes.

cron is a feature originating from Unix cron utility and has various options based on your requirements.

Example usage can be as below:

@Scheduled(fixedDelay =30000)

public void demoServiceMethod () {... }

@Scheduled(fixedRate=30000)

public void demoServiceMethod () {... }

@Scheduled(cron="0 0 * * * *")

public void demoServiceMethod () {... }

To use @Scheduled in your spring application, you must first define below xml namespace and schema location definition in your

application-config.xml file.

xmlns:task="http://www.springframework.org/schema/task"

http://www.springframework.org/schema/task

http://www.springframework.org/schema/task/spring-task-3.0.xsd

Above additions are necessary because we will be using annotation based configurations. Now add below definition to enable

annotations.

<task:annotation-driven>

Next step is to create a class and a method inside the class like below:

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 135/211 |

Page 136: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

public class DemoService

{

@Scheduled(cron="*/5 * * * * ?")

public void demoServiceMethod()

{

System.out.println("Method executed at every 5 seconds. Current time is :: "+ new Date());

}

}

Using @Scheduled annotation would in turn make Spring container understand that the method underneath this annotation would

run as a job.  Remember that the methods annotated with @Scheduled should not have parameters passed to them. They should not

return any values too. If you want the external objects to be used within your @Scheduled methods, you should inject them into the

DemoService class using autowiring rather than passing them as parameters to the @Scheduled methods.

Method 1) Task scheduling using fixed delay attribute in @Scheduled annotation

In this method, fixedDelay attribute is used with @Scheduled annotation. Alternatively, fixedRate can also be used.

A sample class will look like this:

package com.technicalstack.service;

import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;

public class DemoServiceBasicUsageFixedDelay

{

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 136/211 |

Page 137: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

@Scheduled(fixedDelay = 5000)

//@Scheduled(fixedRate = 5000)

public void demoServiceMethod()

{

System.out.println("Method executed at every 5 seconds. Current time is :: "+ new Date());

}

}

And application configuration will look like this:

< ?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:task="http://www.springframework.org/schema/task"

xmlns:util="http://www.springframework.org/schema/util"

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

http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd

http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

<task:annotation-driven />

<bean id="demoServiceBasicUsageFixedDelay" class="com.technicalstack.service.DemoServiceBasicUsageFixedDelay"></bean>

</beans>

Method 2) Task scheduling using cron expression in @Scheduled annotation

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 137/211 |

Page 138: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

In this method, cron attribute is used with @Scheduled annotation. Value of this attribute must be a cron expression.

A sample class will look like this:

package com.technicalstack.service;

import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;

public class DemoServiceBasicUsageCron

{

@Scheduled(cron="*/5 * * * * ?")

public void demoServiceMethod()

{

System.out.println("Method executed at every 5 seconds. Current time is :: "+ new Date());

}

}

And application configuration will look like this:

< ?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:task="http://www.springframework.org/schema/task"

xmlns:util="http://www.springframework.org/schema/util"

xmlns:context="http://www.springframework.org/schema/context"

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 138/211 |

Page 139: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

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

http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd

http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

<task:annotation-driven />

<bean id="demoServiceBasicUsageCron" class="com.technicalstack.service.DemoServiceBasicUsageCron"></bean>

</beans>

Method 3) Task scheduling using cron expression from properties file

In this method, cron attribute is used with @Scheduled annotation. Value of this attribute must be a cron expression as in previous

method, BUT, this cron expression will be defined in a properties file and key of related property will be used in @Scheduled

annotation.

This will decouple the cron expression from source code, thus making changes easy.

A sample class will look like this:

package com.technicalstack.service;

import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;

public class DemoServicePropertiesExample {

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 139/211 |

Page 140: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

@Scheduled(cron = "${cron.expression}")

public void demoServiceMethod()

{

System.out.println("Method executed at every 5 seconds. Current time is :: "+ new Date());

}

}

And application configuration will look like this:

<?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:task="http://www.springframework.org/schema/task"

xmlns:util="http://www.springframework.org/schema/util"

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

http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd

http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

<task:annotation-driven />

<util:properties id="applicationProps" location="application.properties" />

<context:property-placeholder properties-ref="applicationProps" />

<bean id="demoServicePropertiesExample" class="com.technicalstack.service.DemoServicePropertiesExample"></bean>

</beans>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 140/211 |

Page 141: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Method 4) Task scheduling using cron expression configured in context configuration

In this method, cron expression is configured in properties file, and job scheduling is configured in configuration file using property

key for cron expression. Major change is that you do not need to use @Scheduled annotation on any method. Method configuration

is also done in application configuration file.

A sample class will look like this:

package com.technicalstack.service;

import java.util.Date;

public class DemoServiceXmlConfig

{

public void demoServiceMethod()

{

System.out.println("Method executed at every 5 seconds. Current time is :: "+ new Date());

}

}

And application configuration will look like this:

<?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:task="http://www.springframework.org/schema/task"

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 141/211 |

Page 142: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

xmlns:util="http://www.springframework.org/schema/util"

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

http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd

http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

<task:annotation-driven />

<util:properties id="applicationProps" location="application.properties" />

<context:property-placeholder properties-ref="applicationProps" />

<bean id="demoServiceXmlConfig" class="com.technicalstack.service.DemoServiceXmlConfig" />

<task:scheduled-tasks>

<task:scheduled ref="demoServiceXmlConfig" method="demoServiceMethod"

cron="#{applicationProps['cron.expression']}"></task:scheduled>

</task:scheduled-tasks>

</beans>

Download sourcecode for above examples using below link.

13 best practices for writing spring configuration files

Spring is a powerful Java application framework, used in a wide range of configuration options. Its best feature if that it provides

enterprise services to Plain Old Java Objects (POJOs) called beans. Spring uses dependency injection (DI) to achieve simplification

and increased testability. Spring beans, dependencies, and the services needed by beans are specified in xml configuration files or

annotations. The XML configuration files, however, are verbose and more clean. If not planned and written correctly, it becomes

very hard to manage in big projects.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 142/211 |

Page 143: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

In this article, I will show you 10 best practices for writing spring XML configurations. Some of them may seem more necessary

practices rather than best practices, yet I have included them in here because they were highly related to the topic.

Note: Some other factors, such as application design, can impact the XML configuration decisions but I am focusing on the XML

configuration's readability and manageability only.

1) Add a header comment to each configuration file

2) Use consistent naming conventions

3) No version numbers in schema references

4) Prefer setter injection over constructor injection

5) Prefer type over index for constructor argument matching

6) Use shortcut forms over expanded forms

7) Reuse bean definitions as much as possible

8) Always use ids as bean identifiers

9) Try to avoid autowiring

10) Always use classpath prefix

11) Always externalize properties

12) Use dependency-check at the development phase

13) Do not abuse/overuse dependency injection

Lets discuss each of above in detail to make more sense.

1) Add a header comment to each configuration file

I always put more stress on code comments. The same goes for configuration files also. It is always very helpful to add a

configuration file header, which summarizes the beans/properties defined in the configuration files.

In spring configuration, you can add comments as adding xml comments or you can use the description element. For example:

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 143/211 |

Page 144: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<beans>

<description>

This configuration file will have all beans

which may be used for controlling transactions.

</description>

...

</beans>

One possible advantage of using the description tag is that some tools may pick up the description from this element to help you in

other places.

2) Use consistent naming conventions

This is very important thing that you use same naming across all configuration files. Using clear, descriptive, and consistent name

conventions across the project increase the readability of configuration files and make it easy for other developers to avoid some

accidental bugs.

For bean ID, for example, you can follow the Java class field name convention. The bean ID for an instance of

EmployeeUpdateDAO would be employeeUpdateDAO. For large projects, you can add the package name as the prefix of the bean

ID. e.g. finance.employeeUpdateDAO.

3) No version numbers in schema references

I have also pointed out this feature earlier in previous post. I am again including it because it is essential and beneficial in long term

specially to reduce maintainbility. To refresh your memory, specifying version number in bean configuration files for referenced

schemas are not mandatory at all, and you can omit it. If fact, you should omit it all the time.

Spring automatically picks the highest version available from the project dependencies (jars). Also, as the project evolves and the

Spring version will be updated, we won't have to maintain all the XML config files to see the new features.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 144/211 |

Page 145: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Read More: Do not specify version numbers in Spring schema references

A sample example will be like this:

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

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

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

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd">

<!-- Other bean definitions-->

</beans>

4) Prefer setter injection over constructor injection

Spring provides three types of dependency injection: constructor injection, setter injection, and method injection. Usually, we all use

first two types only.

<!-- Constructor injection -->

<bean id="employeeDAO"   class="com.technicalstack.dao.EmployeeDAO">

<constructor-arg ref="datasource"/>

</bean>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 145/211 |

Page 146: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<!-- Setter injection -->

<bean id="employeeDAO" class="com.technicalstack.dao.EmployeeDAO">

<property name="datasource"  ref="datasource">

</bean>

Constructor injection can provide the cheapest thread safety possible i.e. immutable object. Also it guarantees that object will not be

handed over to other beans without complete initialization.

Setter injection provides much desired capability i.e. flexibility or maintainability. If there are multiple attributes to set in a bean,

then creating a long list of parameters to constructor is not good idea. Also, if is possible that some of the attributes might be

optional.

Prefer flexibility. For immutability or thread safety, follow other programming rules.

Read More: How to make a java class immutable

5) Prefer type over index for constructor argument matching in Constructor injection

Better to avoid constructor injection and prefer to use setter injection for dependency injection. But, if you have an absolute

requirement to use constructor injection then always prefer parameter matching based on type rather than index.

<!-- Index based constructor injection -->

<bean id="employeeDAO" class="com.technicalstack.EmployeeDAO">

<constructor-arg index="0" value="rest"/>

<constructor-arg index="1" value="8080"/>

</bean>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 146/211 |

Page 147: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<!-- Type based constructor injection -->

<bean id="employeeDAO" class="com.technicalstack.EmployeeDAO">

<constructor-arg type="java.lang.String" value="rest"/>

<constructor-arg type="int" value="8080"/>

</bean>

As you can see that type based argument passing is more readable and less error prone. But, anytime there is any ambiguity in type

based argument passing, go to index based argument passing without hesitation.

6) Use shortcut forms over expanded forms

Spring bean configuration semantics allow two forms for specifying property values and other bean references. One is expanded and

other is shorter form. Prefer shorter version.

<!-- Expanded version -->

<bean id="employeeDAO" class="com.technicalstack.dao.EmployeeDAO">

<property name="datasource">

<ref bean="datasource"></ref>

<value>datasource</value>

</property>

</bean>

<!-- Shorter/shortcut version -->

<bean id="employeeDAO" class="com.technicalstack.dao.EmployeeDAO">

<property name="datasource"  ref="datasource" value="datasource">

</bean>

7) Reuse bean definitions as much as possible

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 147/211 |

Page 148: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Spring provides a very useful capability which you should use extensively in your project and i.e. bean definition re-usability. Here I

am not talking about bean references for setter injection. Rather I am pointing out the bean definition re-use in constructing other

beans.

Take an example of datasource definition:

<bean id="abstractDataSource" class="org.apache.commons.dbcp.BasicDataSource"

destroy-method="close"

p:driverClassName="${jdbc.driverClassName}"

p:username="${jdbc.username}"

p:password="${jdbc.password}" />

<bean id="concreteDataSourceOne"

parent="abstractDataSource"

p:url="${jdbc.databaseurlOne}"/>

<bean id="concreteDataSourceTwo"

parent="abstractDataSource"

p:url="${jdbc.databaseurlTwo}"/>

Read complete configuration example here: Spring 3.2.5 AbstractRoutingDataSource example

8) Always use ids as bean identifiers

Spring allows two types of identifiers for a bean. Using attribute ?id? or by ?name?. You should always choose attribute id over

name. Usually it does neither increase readability nor benefit any performance scenario. It is just industry standard practice which all

fellow developers are following worldwide and even in your team.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 148/211 |

Page 149: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Just don't be odd man out here.

9) Try to avoid autowiring

Autowiring is a great feature if you can manage it in long term. Usually it is beneficial if you project is having very few beans and

you can almost remember them all in your memory as well.

As soon as project gets bigger, autowiring starts creating trouble in identifying correct dependency to use. The main drawback, I find

is not to have a overview of whole system binded together. This is where spring configuration files win. They can represent the

whole system to any new guy in couple of minutes.

Also, when you start debugging some complex issues then all information present in one place in configuration files, actually helps a

lot. Autowiring makes debugging harder.

Read More: Spring autowiring concepts

10) Always use classpath prefix

When importing resources, XML config, properties, etc. Always use the classpath: or classpath*: prefix. This provides consistency

and clarity to the location of the resource. Not every feature of Spring behaves the same, classpath: guarantees consistency.

The classpath is determined by the build tool and IDE. Usually this is src/main/java for java code, src/main/resources for non-java

dependencies and for tests, src/test/java for java code and src/test/resources for non-java resources.

<!-- Always use classpath: prefix-->

<import resource="classpath:/META-INF/spring/applicationContext-security.xml"/>

11) Always externalize properties

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 149/211 |

Page 150: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Often there are multiple configuration parameters related to runtime of application. They are passed to bean definitions in bean

configuration context file. DO not hard code them in config file. Instead externalize them to some properties file(s).

Better group them in separate files based on their usage or module i.e. all JDBC datasource related properties in jdbc.properties file.

<bean id="abstractDataSource" class="org.apache.commons.dbcp.BasicDataSource"

destroy-method="close"

p:driverClassName="${jdbc.driverClassName}"

p:username="${jdbc.username}"

p:password="${jdbc.password}" />

and properties file

/* file://jdbc.properties */

jdbc.driverClassName=com.mysql.jdbc.Driver

jdbc.username=root

jdbc.password=password

12) Use dependency-check at the development phase

You should mostly set the dependency-check attribute on a bean definition to simple, objects, or all (default value is none i.e. no

checking), so that the container can do explicit dependency validation for you. It is useful when all of the properties (or certain

categories of properties) of a bean must be set explicitly, or via autowiring.

<bean id="abstractDataSource" class="org.apache.commons.dbcp.BasicDataSource"

destroy-method="close"

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 150/211 |

Page 151: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

p:driverClassName="${jdbc.driverClassName}"

p:username="${jdbc.username}"

p:password="${jdbc.password}"

dependency-check="all" />

In above given example, the container will ensure that all properties/parameters to datasource are set in application initialization

time itself.

13) Do not abuse/overuse dependency injection

Finally, please do not abuse the motive behind introducing dependency injection. Java provide ?new? keyword to create new

objects. Use this wonderful keyword where DI is not necessary e.g. DTO objects. Don't try to play smarter. Just follow the basics.

Difference between context:component-scan and context:annotation-config in Spring

<context:component-scan/> scan packages and classes within given base packages then find and register beans into

ApplicationContext.It does all things that <context:annotation-config/> is supposed to do.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 151/211 |

Page 152: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

So if you have used annotation for example, @Autowired in your code and <context:component-scan/> in xml then You do not

require to use <context:annotation-config/>

<context:annotation-config /> only works on bean which are already registered on ApplicationContext.Doesn't matter they were

registered using xml or annotations.And it's for only some of annotation which I have mentioned below.  So If you have used

@Autowired in your code and beans are registered either using xml or @Configuration then you can use

<contex:annotationconfig/>.

<context:annotation-config />  registers only 4 BeanPostProcessors which are part of the Spring Framework and They are follows as

:

- CommonAnnotationBeanPostProcessor :

Recognizes and processes the JSR 250 common annotations (@PostConstruct, @PreDestroy, @Resource)

- AutowiredAnnotationBeanPostProcessor :

Recognizes the Autowired related annotations (@Autowired, @Value, @Inject, @Qualifier, etc)

- RequiredAnnotationBeanPostProcessor :

Recognizes the @Required annotation

- PersistenceAnnotationBeanPostProcessor :

Recognizes the @PersistenceUnit and @PersistenceContext annotations (related to JPA) etc.

If I have missed any annotationPostProcessor here then let me know.

<context:component-scan/> annotation is a super set of the <context:annotation-config/> meaning it registers all those bean post

processors which are mentioned above with addition of other annotation and also scan classes which are annotated with category of

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 152/211 |

Page 153: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

annotations (@Component, @Repository, @Controller, etc).

You should either use only one, I usually prefer to use <context:component-scan/>

Spring MVC: Difference between <context:annotation-config> vs <context:component-scan>

We have already learned few things in Spring MVC in previous posts. In those tutorials, I did use tags like

<context:annotation-config> or <context:component-scan>, but I didn't explained much in detail about these tags. I am writing this

post, specifically to list down the difference between tags <context:annotation-config> and <context:component-scan> so that when

you use them in future, you will know, what exactly are you doing.

1) First big difference between both tags is that <context:annotation-config> is used to activate applied annotations in already

registered beans in application context. Note that it simply does not matter whether bean was registered by which mechanism e.g.

using <context:component-scan> or it was defined in application-context.xml file itself.

2) Second difference is driven from first difference itself. It does register the beans in context + it also scans the annotations inside

beans and activate them. So <context:component-scan> does what <context:annotation-config> does, but additionally it scan the

packages and register the beans in application context.

Example of <context:annotation-config> vs <context:component-scan> uses

I will elaborate both tags in detail with some examples which will make more sense to us. For keeping the example to simple, I am

creating just 3 beans, and I will try to configure them in configuration file in various ways, then we will see the difference between

various configurations in console where output will get printed.

For reference, below are 3 beans. BeanA has reference to BeanB and BeanC additionally.

package com.technicalstack.beans;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 153/211 |

Page 154: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

@SuppressWarnings("unused")

@Component

public class BeanA {

private BeanB beanB;

private BeanC beanC;

public BeanA(){

System.out.println("Creating bean BeanA");

}

@Autowired

public void setBeanB(BeanB beanB) {

System.out.println("Setting bean reference for BeanB");

this.beanB = beanB;

}

@Autowired

public void setBeanC(BeanC beanC) {

System.out.println("Setting bean reference for BeanC");

this.beanC = beanC;

}

}

//Bean B

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 154/211 |

Page 155: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

package com.technicalstack.beans;

import org.springframework.stereotype.Component;

@Component

public class BeanB {

public BeanB(){

System.out.println("Creating bean BeanB");

}

}

//Bean C

package com.technicalstack.beans;

import org.springframework.stereotype.Component;

@Component

public class BeanC {

public BeanC(){

System.out.println("Creating bean BeanC");

}

}

BeanDemo class is used to load and initialize the application context.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 155/211 |

Page 156: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

package com.technicalstack.test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanDemo {

public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext("classpath:beans.xml");

}

}

Now let's start writing the configuration file "beans.xml" with variations. I will be omitting the schema declarations in below

examples, to keep focus on configuration itself.

- a) Define only bean tags

<bean id="beanA" class="com.technicalstack.beans.BeanA"></bean>

<bean id="beanB" class="com.technicalstack.beans.BeanB"></bean>

<bean id="beanC" class="com.technicalstack.beans.BeanC"></bean>

Output:

Creating bean BeanA

Creating bean BeanB

Creating bean BeanC

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 156/211 |

Page 157: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

In this case, all 3 beans are created and no dependency in injected in BeanA because we didn't used any property/ref attributes.

- b) Define bean tags and property ref attributes

<bean id="beanA" class="com.technicalstack.beans.BeanA">

<property name="beanB" ref="beanB"></property>

<property name="beanC" ref="beanC"></property>

</bean>

<bean id="beanB" class="com.technicalstack.beans.BeanB"></bean>

<bean id="beanC" class="com.technicalstack.beans.BeanC"></bean>

Output:

Creating bean BeanA

Creating bean BeanB

Creating bean BeanC

Setting bean reference for BeanB

Setting bean reference for BeanC

Now the beans are created and injected as well. No wonder.

- c) Using only <context:annotation-config />

<context:annotation-config />

//No Output

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 157/211 |

Page 158: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

As I told already, <context:annotation-config /> activate the annotations only on beans which have already been discovered and

registered. Here, we have not discovered any bean so nothing happened.

- d) Using <context:annotation-config /> with bean declarations

<context:annotation-config />

<bean id="beanA" class="com.technicalstack.beans.BeanA"></bean>

<bean id="beanB" class="com.technicalstack.beans.BeanB"></bean>

<bean id="beanC" class="com.technicalstack.beans.BeanC"></bean>

Output:

Creating bean BeanA

Creating bean BeanB

Setting bean reference for BeanB

Creating bean BeanC

Setting bean reference for BeanC

In above configuration, we have discovered the beans using <bean> tags. Now when we use <context:annotation-config />, it simply

activates @Autowired annotation and bean injection inside BeanA happens.

- e) Using only <context:component-scan />

<context:component-scan base-package="com.technicalstack.beans" />

Output:

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 158/211 |

Page 159: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Creating bean BeanA

Creating bean BeanB

Setting bean reference for BeanB

Creating bean BeanC

Setting bean reference for BeanC

Above configuration does both things as I mentioned earlier in start of post. It does the bean discovery (searches for @Component

annotation in base package) and then activates the additional annotations (e.g. Autowired).

- f) Using both <context:component-scan /> and <context:annotation-config />

<context:annotation-config />

<context:component-scan base-package="com.technicalstack.beans" />

<bean id="beanA" class="com.technicalstack.beans.BeanA"></bean>

<bean id="beanB" class="com.technicalstack.beans.BeanB"></bean>

<bean id="beanC" class="com.technicalstack.beans.BeanC"></bean>

Output:

Creating bean BeanA

Creating bean BeanB

Setting bean reference for BeanB

Creating bean BeanC

Setting bean reference for BeanC

Strange !! With above configuration we are discovering beans two times and activating annotations two times as well. But output got

printed one time only. Why? Because spring is intelligent enough to register any configuration processing only once if it is

registered multiple tiles using same or different ways. Cool !!

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 159/211 |

Page 160: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Spring JdbcTemplate

 

Spring JdbcTemplate internally uses JDBC api, but eliminates a lot of problems of JDBC API.

Problems of JDBC API

- We need to write a lot of code before and after executing the query, such as creating connection, statement, closing

resultset, connection etc.

- We need to perform exception handling code on the database logic.

- We need to handle transaction.

- Repetition of all these codes from one to another database logic is a time consuming task.

- Advantage of Spring JdbcTemplate

Spring JdbcTemplate eliminates all the above mentioned problems of JDBC API. It provides you methods to write       the queries

directly, so it saves a lot of work and time.

Spring Jdbc Approaches

Spring framework provides following approaches for JDBC database access:

- JdbcTemplate

- NamedParameterJdbcTemplate

- SimpleJdbcTemplate

- SimpleJdbcInsert and SimpleJdbcCall

JdbcTemplate class

- It is the central class in the Spring JDBC support classes. It takes care of creation and release of resources such as creating

and closing of connection object etc. So it will not lead to any problem if you forget to close the connection.

- It handles the exception and provides the informative exception messages by the help of excepion classes defined in the

org.springframework.dao package.

- We can perform all the database operations by the help of JdbcTemplate class such as insertion, updation, deletion and

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 160/211 |

Page 161: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

retrieval of the data from the database.

Methods of spring JdbcTemplate class.

Example of Spring JdbcTemplate

We are assuming that you have created the following table inside the Oracle10g database.

create table employee(

id number(10),

name varchar2(100),

salary number(10)

);

Employee.java

This class contains 3 properties with constructors and setter and getters.

package com.javatpoint;

public class Employee {

private int id;

private String name;

private float salary;

//no-arg and parameterized constructors

//getters and setters

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 161/211 |

Page 162: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

EmployeeDao.java

 

It contains one property jdbcTemplate and three methods saveEmployee(), updateEmployee and deleteEmployee().

package com.javatpoint;

import org.springframework.jdbc.core.JdbcTemplate;

public class EmployeeDao {

private JdbcTemplate jdbcTemplate;

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {

this.jdbcTemplate = jdbcTemplate;

}

public int saveEmployee(Employee e){

String query="insert into employee values(

'"+e.getId()+"','"+e.getName()+"','"+e.getSalary()+"')";

return jdbcTemplate.update(query);

}

public int updateEmployee(Employee e){

String query="update employee set

name='"+e.getName()+"',salary='"+e.getSalary()+"' where id='"+e.getId()+"' ";

return jdbcTemplate.update(query);

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 162/211 |

Page 163: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

public int deleteEmployee(Employee e){

String query="delete from employee where id='"+e.getId()+"' ";

return jdbcTemplate.update(query);

}

}

applicationContext.xml

- The DriverManagerDataSource is used to contain the information about the database such as driver class name, connnection

URL, username and password.

- There are a property named datasource in the JdbcTemplate class of DriverManagerDataSource type. So, we need to

provide the reference of DriverManagerDataSource object in the JdbcTemplate class for the datasource property.

Here, we are using the JdbcTemplate object in the EmployeeDao class, so we are passing it by the setter method but you can use

constructor also.

<?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="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 163/211 |

Page 164: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />

<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />

<property name="username" value="system" />

<property name="password" value="oracle" />

</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> 

<property name="dataSource" ref="ds"></property> 

</bean> 

 

<bean id="edao" class="com.javatpoint.EmployeeDao"> 

<property name="jdbcTemplate" ref="jdbcTemplate"></property> 

</bean> 

</beans>

Test.java

This class gets the bean from the applicationContext.xml file and calls the saveEmployee() method. You can also call

updateEmployee() and deleteEmployee() method by uncommenting the code as well.

package com.javatpoint;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 164/211 |

Page 165: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

public static void main(String[] args) {

ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");

EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");

int status=dao.saveEmployee(new Employee(102,"Amit",35000));

System.out.println(status);

/*int status=dao.updateEmployee(new Employee(102,"Sonoo",15000));

System.out.println(status);

*/

/*Employee e=new Employee();

e.setId(102);

int status=dao.deleteEmployee(e);

System.out.println(status);*/

}

}

ResultSetExtractor Example | Fetching Records by Spring JdbcTemplate

 

We can easily fetch the records from the database using query() method of JdbcTemplate class where we need to pass the instance

of ResultSetExtractor

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 165/211 |

Page 166: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Syntax of query method using ResultSetExtractor

public T query(String sql,ResultSetExtractor<T> rse) 

ResultSetExtractor Interface

ResultSetExtractor interface can be used to fetch records from the database. It accepts a ResultSet and returns the list.

Method of ResultSetExtractor interface

It defines only one method extractData that accepts ResultSet instance as a parameter. Syntax of the method is given below:

        public T extractData(ResultSet rs)throws SQLException,DataAccessException

- Example of ResultSetExtractor Interface to show all the records of the table

Assuming that you have created the following table inside the Oracle10g database.

create table employee(

id number(10),

name varchar2(100),

salary number(10)

);

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 166/211 |

Page 167: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Employee.java

This class contains 3 properties with constructors and setter and getters. It defines one extra method toString().

package com.javatpoint;

public class Employee {

private int id;

private String name;

private float salary;

//no-arg and parameterized constructors

//getters and setters

public String toString(){

return id+" "+name+" "+salary;

}

}

EmployeeDao.java

It contains one property jdbcTemplate and one method getAllEmployees.

package com.javatpoint;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 167/211 |

Page 168: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

import org.springframework.dao.DataAccessException;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.core.ResultSetExtractor;

public class EmployeeDao {

private JdbcTemplate template;

public void setTemplate(JdbcTemplate template) {

this.template = template;

}

public List<Employee> getAllEmployees(){

return template.query("select * from employee",new ResultSetExtractor<List<Employee>>(){

@Override

public List<Employee> extractData(ResultSet rs) throws SQLException,

DataAccessException {

List<Employee> list=new ArrayList<Employee>();

while(rs.next()){

Employee e=new Employee();

e.setId(rs.getInt(1));

e.setName(rs.getString(2));

e.setSalary(rs.getInt(3));

list.add(e);

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 168/211 |

Page 169: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

return list;

}

});

}

}

ApplicationContext.xml

- The DriverManagerDataSource is used to contain the information about the database such as driver class name, connnection

URL, username and password.

- There are a property named datasource in the JdbcTemplate class of DriverManagerDataSource type. So, we need to

provide the reference of DriverManagerDataSource object in the JdbcTemplate class for the datasource property.

- Here, we are using the JdbcTemplate object in the EmployeeDao class, so we are passing it by the setter method but you can

use constructor also.

<?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="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />

<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 169/211 |

Page 170: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<property name="username" value="system" />

<property name="password" value="oracle" />

</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">

<property name="dataSource" ref="ds"></property>

</bean>

<bean id="edao" class="com.javatpoint.EmployeeDao">

<property name="jdbcTemplate" ref="jdbcTemplate"></property>

</bean>

</beans>

Test.java

This class gets the bean from the applicationContext.xml file and calls the getAllEmployees() method of EmployeeDao class.

package com.javatpoint;

import java.util.List;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

public static void main(String[] args) {

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 170/211 |

Page 171: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");

EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");

List<Employee> list=dao.getAllEmployees();

for(Employee e:list)

System.out.println(e);

}

}

RowMapper Example | Fetching records by Spring JdbcTemplate

- Like ResultSetExtractor, we can use RowMapper interface to fetch the records from the database using query() method of

JdbcTemplate class. In the execute of we need to pass the instance of RowMapper now.

Syntax of query method using RowMapper

public T query(String sql,RowMapper<T> rm)

RowMapper Interface

- RowMapper interface allows to map a row of the relations with the instance of user-defined class. It iterates the ResultSet

internally and adds it into the collection. So we don't need to write a lot of code to fetch the records as ResultSetExtractor.

Advantage of RowMapper over ResultSetExtractor

- RowMapper saves a lot of code becuase it internally adds the data of ResultSet into the collection.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 171/211 |

Page 172: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Method of RowMapper interface

- It defines only one method mapRow that accepts ResultSet instance and int as the parameter list. Syntax of the method is

given below:

public T mapRow(ResultSet rs, int rowNumber)throws SQLException

Example of RowMapper Interface to show all the records of the table

We are assuming that you have created the following table inside the Oracle10g database.

create table employee(

id number(10),

name varchar2(100),

salary number(10)

);

Employee.java

This class contains 3 properties with constructors and setter and getters and one extra method toString().

package com.javatpoint;

public class Employee {

private int id;

private String name;

private float salary;

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 172/211 |

Page 173: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

//no-arg and parameterized constructors

//getters and setters

public String toString(){

return id+" "+name+" "+salary;

}

}

EmployeeDao.java

It contains on property jdbcTemplate and one method getAllEmployeesRowMapper.

package com.javatpoint;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;

import org.springframework.dao.DataAccessException;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.core.ResultSetExtractor;

import org.springframework.jdbc.core.RowMapper;

public class EmployeeDao {

private JdbcTemplate template;

public void setTemplate(JdbcTemplate template) {

this.template = template;

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 173/211 |

Page 174: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

public List<Employee> getAllEmployeesRowMapper(){

return template.query("select * from employee",new RowMapper<Employee>(){

@Override

public Employee mapRow(ResultSet rs, int rownumber) throws SQLException {

Employee e=new Employee();

e.setId(rs.getInt(1));

e.setName(rs.getString(2));

e.setSalary(rs.getInt(3));

return e;

}

});

}

}

applicationContext.xml

- The DriverManagerDataSource is used to contain the information about the database such as driver class name, connnection

URL, username and password.

- There are a property named datasource in the JdbcTemplate class of DriverManagerDataSource type. So, we need to

provide the reference of DriverManagerDataSource object in the JdbcTemplate class for the datasource property.

- Here, we are using the JdbcTemplate object in the EmployeeDao class, so we are passing it by the setter method but you can

use constructor also.

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

<beans

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

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 174/211 |

Page 175: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

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="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />

<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />

<property name="username" value="system" />

<property name="password" value="oracle" />

</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">

<property name="dataSource" ref="ds"></property>

</bean>

<bean id="edao" class="com.javatpoint.EmployeeDao">

<property name="jdbcTemplate" ref="jdbcTemplate"></property>

</bean>

</beans>

Test.java

This class gets the bean from the applicationContext.xml file and calls the getAllEmployeesRowMapper() method of

EmployeeDao class.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 175/211 |

Page 176: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

package com.javatpoint;

import java.util.List;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

public static void main(String[] args) {

ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");

EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");

List<Employee> list=dao.getAllEmployeesRowMapper();

for(Employee e:list)

System.out.println(e);

}

}

Spring NamedParameterJdbcTemplate

- Spring provides another way to insert data by named parameter. In such way, we use names instead of ?(question mark). So

it is better to remember the data for the column.

Simple example of named parameter query

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 176/211 |

Page 177: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

insert into employee values (:id,:name,:salary)

Method of NamedParameterJdbcTemplate class

In this example,we are going to call only the execute method of NamedParameterJdbcTemplate class. Syntax of the method is as

follows:

public T execute(String sql,Map map,PreparedStatementCallback psc)

Example of NamedParameterJdbcTemplate class

create table employee(

id number(10),

name varchar2(100),

salary number(10)

);

Employee.java

This class contains 3 properties with constructors and setter and getters.

package com.javatpoint;

public class Employee {

private int id;

private String name;

private float salary;

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 177/211 |

Page 178: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

//no-arg and parameterized constructors

//getters and setters

}

EmployeeDao.java

It contains on property jdbcTemplate and one method save.

package com.javatpoint;

import java.sql.PreparedStatement;

import java.sql.SQLException;

import org.springframework.dao.DataAccessException;

import org.springframework.jdbc.core.PreparedStatementCallback;

import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import java.util.*;

public class EmpDao {

NamedParameterJdbcTemplate template;

public EmpDao(NamedParameterJdbcTemplate template) {

this.template = template;

}

public  void save (Emp e){

String query="insert into employee values (:id,:name,:salary)";

Map<String,Object> map=new HashMap<String,Object>();

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 178/211 |

Page 179: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

map.put("id",e.getId());

map.put("name",e.getName());

map.put("salary",e.getSalary());

template.execute(query,map,new PreparedStatementCallback() {

@Override

public Object doInPreparedStatement(PreparedStatement ps)

throws SQLException, DataAccessException {

return ps.executeUpdate();

}

});

}

}

applicationContext.xml

- The DriverManagerDataSource is used to contain the information about the database such as driver class name, connnection

URL, username and password.

- There are a property named datasource in the NamedParameterJdbcTemplate class of DriverManagerDataSource type. So,

we need to provide the reference of DriverManagerDataSource object in the NamedParameterJdbcTemplate class for the

datasource property.

- Here, we are using the NamedParameterJdbcTemplate object in the EmployeeDao class, so we are passing it by the

constructor but you can use setter method also.

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

<beans

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

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 179/211 |

Page 180: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

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="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />

<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />

<property name="username" value="system" />

<property name="password" value="oracle" />

</bean>

<bean id="jtemplate"

class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">

<constructor-arg ref="ds"></constructor-arg>

</bean>

<bean id="edao" class="com.javatpoint.EmpDao">

<constructor-arg>

<ref bean="jtemplate"/>

</constructor-arg>

</bean>

</beans>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 180/211 |

Page 181: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

SimpleTest.java

This class gets the bean from the applicationContext.xml file and calls the save method.

package com.javatpoint;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.ClassPathResource;

import org.springframework.core.io.Resource;

public class SimpleTest {

public static void main(String[] args) {

Resource r=new ClassPathResource("applicationContext.xml");

BeanFactory factory=new XmlBeanFactory(r);

EmpDao dao=(EmpDao)factory.getBean("edao");

dao.save(new Emp(23,"sonoo",50000));

}

}

Spring SimpleJdbcTemplate

 

Spring 3 JDBC supports the java 5 feature var-args (variable argument) and autoboxing by the help of SimpleJdbcTemplate class.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 181/211 |

Page 182: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

- SimpleJdbcTemplate class wraps the JdbcTemplate class and provides the update method where we can pass arbitrary

number of arguments.

Syntax of update method of SimpleJdbcTemplate class

int update(String sql,Object... parameters)

We should pass the parameter values in the update method in the order they are defined in the parameterized query.

Example of SimpleJdbcTemplate class

We are assuming that you have created the following table inside the Oracle10g database.

create table employee(

id number(10),

name varchar2(100),

salary number(10)

);

Employee.java

This class contains 3 properties with constructors and setter and getters.

package com.javatpoint;

public class Employee {

private int id;

private String name;

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 182/211 |

Page 183: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

private float salary;

//no-arg and parameterized constructors

//getters and setters

}

EmployeeDao.java

It contains one property SimpleJdbcTemplate and one method update. In such case, update method will update only name for the

corresponding id. If you want to update the name and salary both, comment the above two lines of code of the update method and

uncomment the 2 lines of code given below.

package com.javatpoint;

import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

public class EmpDao {

SimpleJdbcTemplate template;

public EmpDao(SimpleJdbcTemplate template) {

this.template = template;

}

public int update (Emp e){

String query="update employee set name=? where id=?";

return template.update(query,e.getName(),e.getId());

//String query="update employee set name=?,salary=? where id=?";

//return template.update(query,e.getName(),e.getSalary(),e.getId());

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 183/211 |

Page 184: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

}

applicationContext.xml

- The DriverManagerDataSource is used to contain the information about the database such as driver class name, connnection

URL, username and password.

- There are a property named datasource in the SimpleJdbcTemplate class of DriverManagerDataSource type. So, we need to

provide the reference of DriverManagerDataSource object in the SimpleJdbcTemplate class for the datasource property.

- Here, we are using the SimpleJdbcTemplate object in the EmployeeDao class, so we are passing it by the constructor but

you can use setter method also.

<?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="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />

<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />

<property name="username" value="system" />

<property name="password" value="oracle" />

</bean>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 184/211 |

Page 185: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<bean id="jtemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">

<constructor-arg ref="ds"></constructor-arg>

</bean>

<bean id="edao" class="com.javatpoint.EmpDao">

<constructor-arg>

<ref bean="jtemplate"/>

</constructor-arg>

</bean>

</beans>

SimpleTest.java

This class gets the bean from the applicationContext.xml file and calls the update method of EmpDao class.

package com.javatpoint;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.ClassPathResource;

import org.springframework.core.io.Resource;

public class SimpleTest {

public static void main(String[] args) {

Resource r=new ClassPathResource("applicationContext.xml");

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 185/211 |

Page 186: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

BeanFactory factory=new XmlBeanFactory(r);

EmpDao dao=(EmpDao)factory.getBean("edao");

int status=dao.update(new Emp(23,"Tarun",35000));

System.out.println(status);

}

}

Spring with ORM Frameworks

 

Spring provides API to easily integrate Spring with ORM frameworks such as Hibernate, JPA(Java Persistence API), JDO(Java Data

Objects), Oracle Toplink and iBATIS.

Advantage of ORM Frameworks with Spring

There are a lot of advantage of Spring framework in respect to ORM frameworks. There are as follows:

- Less coding is required: By the help of Spring framework, you don't need to write extra codes before and after the actual

database logic such as getting the connection, starting transaction, commiting transaction, closing connection etc.

- Easy to test: Spring's IoC approach makes it easy to test the application.

- Better exception handling: Spring framework provides its own API for exception handling with ORM framework.

- Integrated transaction management: By the help of Spring framework, we can wrap our mapping code with an explicit

template wrapper class or AOP style method interceptor.

Hibernate and Spring Integration

- We can simply integrate hibernate application with spring application.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 186/211 |

Page 187: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

- In hibernate framework, we provide all the database information hibernate.cfg.xml file.

- But if we are going to integrate the hibernate application with spring, we don't need to create the hibernate.cfg.xml file. We

can provide all the information in the applicationContext.xml file.

Advantage of Spring framework with hibernate

- The Spring framework provides HibernateTemplate class, so you don't need to follow so many steps like create

Configuration, BuildSessionFactory, Session, beginning and committing transaction etc.

So it saves a lot of code.

Understanding problem without using spring:

Let's understand it by the code of hibernate given below:

//creating configuration

Configuration cfg=new Configuration();

cfg.configure("hibernate.cfg.xml");

//creating seession factory object

SessionFactory factory=cfg.buildSessionFactory();

//creating session object

Session session=factory.openSession();

//creating transaction object

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 187/211 |

Page 188: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Transaction t=session.beginTransaction();

Employee e1=new Employee(111,"arun",40000);

session.persist(e1);//persisting the object

t.commit();//transaction is commited

session.close();

As you can see in the code of sole hibernate, you have to follow so many steps.

Solution by using HibernateTemplate class of Spring Framework:

Now, you don't need to follow so many steps. You can simply write this:

Employee e1=new Employee(111,"arun",40000);

hibernateTemplate.save(e1);

Methods of HibernateTemplate class

Let's see a list of commonly used methods of HibernateTemplate class.

Example of Hibernate and spring integration

1) create the table in the database

In this example, we are using the Oracle as the database, but you may use any database. Let's create the table in the oracle database

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 188/211 |

Page 189: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

CREATE TABLE  "EMP558"

(    "ID" NUMBER(10,0) NOT NULL ENABLE,

"NAME" VARCHAR2(255 CHAR),

"SALARY" FLOAT(126),

PRIMARY KEY ("ID") ENABLE

)

2) Employee.java

It is a simple POJO class. Here it works as the persistent class for hibernate.

package com.javatpoint;

public class Employee {

private int id;

private String name;

private float salary;

//getters and setters

}

3) employee.hbm.xml

This mapping file contains all the information of the persistent class.

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

<!DOCTYPE hibernate-mapping PUBLIC

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 189/211 |

Page 190: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="com.javatpoint.Employee" table="emp558">

<id name="id">

<generator class="assigned"></generator>

</id>

<property name="name"></property>

<property name="salary"></property>

</class>

</hibernate-mapping>

4) EmployeeDao.java

It is a java class that uses the HibernateTemplate class method to persist the object of Employee class.

package com.javatpoint;

import org.springframework.orm.hibernate3.HibernateTemplate;

import java.util.*;

public class EmployeeDao {

HibernateTemplate template;

public void setTemplate(HibernateTemplate template) {

this.template = template;

}

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 190/211 |

Page 191: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

//method to save employee

public void saveEmployee(Employee e){

template.save(e);

}

//method to update employee

public void updateEmployee(Employee e){

template.update(e);

}

//method to delete employee

public void deleteEmployee(Employee e){

template.delete(e);

}

//method to return one employee of given id

public Employee getById(int id){

Employee e=(Employee)template.get(Employee.class,id);

return e;

}

//method to return all employees

public List<Employee> getEmployees(){

List<Employee> list=new ArrayList<Employee>();

list=template.loadAll(Employee.class);

return list;

}

}

5) applicationContext.xml

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 191/211 |

Page 192: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

- In this file, we are providing all the informations of the database in the BasicDataSource object. This object is used in the

LocalSessionFactoryBean class object, containing some other informations such as mappingResources and

hibernateProperties. The object of LocalSessionFactoryBean class is used in the HibernateTemplate class. Let's see the code

of applicationContext.xml file.

hibernate template

File: applicationContext.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"

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="dataSource" class="org.apache.commons.dbcp.BasicDataSource">

<property name="driverClassName"  value="oracle.jdbc.driver.OracleDriver"></property>

<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></property>

<property name="username" value="system"></property>

<property name="password" value="oracle"></property>

</bean>

<bean id="mysessionFactory"  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

<property name="dataSource" ref="dataSource"></property>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 192/211 |

Page 193: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<property name="mappingResources">

<list>

<value>employee.hbm.xml</value>

</list>

</property>

<property name="hibernateProperties">

<props>

<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>

<prop key="hibernate.hbm2ddl.auto">update</prop>

<prop key="hibernate.show_sql">true</prop>

</props>

</property>

</bean>

<bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">

<property name="sessionFactory" ref="mysessionFactory"></property>

</bean>

<bean id="d" class="com.javatpoint.EmployeeDao">

<property name="template" ref="template"></property>

</bean>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 193/211 |

Page 194: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

</beans>

6) InsertTest.java

This class uses the EmployeeDao class object and calls its saveEmployee method by passing the object of Employee class.

package com.javatpoint;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.ClassPathResource;

import org.springframework.core.io.Resource;

public class InsertTest {

public static void main(String[] args) {

Resource r=new ClassPathResource("applicationContext.xml");

BeanFactory factory=new XmlBeanFactory(r);

EmployeeDao dao=(EmployeeDao)factory.getBean("d");

Employee e=new Employee();

e.setId(114);

e.setName("varun");

e.setSalary(50000);

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 194/211 |

Page 195: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

dao.saveEmployee(e);

}

}

Now, if you see the table in the oracle database, record is inserted successfully.

Enabling automatic table creation, showing sql queries etc.

You can enable many hibernate properties like automatic table creation by hbm2ddl.auto etc. in applicationContext.xml file. Let's

see the code:

<property name="hibernateProperties">

<props>

<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>

<prop key="hibernate.hbm2ddl.auto">update</prop>

<prop key="hibernate.show_sql">true</prop>

</props>

If you write this code, you don't need to create table because table will be created automatically.

How to load multiple Spring bean configuration file

When you are working on large project where stracturized  folder structure is being used for Spring Beans configuration files ex.

Spring-Core.xml in Core Folder, Spring-Common.xml in Common folder etc

You may load multiple Spring bean configuration files in code :

ApplicationContext context =

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 195/211 |

Page 196: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

new ClassPathXmlApplicationContext(new String[] {"Spring-Core.xml",

"Spring-Common.xml"});

This way is not properly organized.It will be better if we can import multiple xml into one xml and then define single main XML

into ClassPathXmlApplicationContext

Ex.

<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-2.5.xsd">

<import resource="common/Spring-Core.xml"/>

<import resource="connection/Spring-Common.xml"/>

</beans>

Load Spring-Main.xml as

ApplicationContext context = new ClassPathXmlApplicationContext(Spring-Main.xml);

Or put xml under project classpath.  project-classpath/Spring-Main.xml

Spring MVC

Spring MVC flow:

Spring MVC 3.2 Execution Flow

- Step 1: First request will be received by DispatcherServlet

- Step 2: DispatcherServlet will take the help of HandlerMapping to know the Controller class name associated with the given

request

- Step 3: So request transfer to the Controller, and then controller will process the request by executing appropriate methods

and returns ModeAndView object (contains Model data and View name) back to the DispatcherServlet

- Step 4: Now DispatcherServlet send the model object to the ViewResolver to get the actual view page

- Step 5: Finally DispatcherServlet will pass the Model object to the View page to display the result

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 196/211 |

Page 197: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

All the above mentioned components ie. HandlerMapping, Controller and ViewResolver are parts ofWebApplicationContext which

is an extension of the plain ApplicationContext with some extra features necessary for web applications.

Required Configuration: in web.xml

<web-app id="WebApp_ID" version="2.4"

xmlns="http://java.sun.com/xml/ns/j2ee"

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

xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee

http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<display-name>Spring MVC Application</display-name>

<servlet>

<servlet-name>HelloWeb</servlet-name>

<servlet-class>

org.springframework.web.servlet.DispatcherServlet

</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>HelloWeb</servlet-name>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 197/211 |

Page 198: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<url-pattern>*.jsp</url-pattern>

</servlet-mapping>

</web-app>

Upon initialization of HelloWeb DispatcherServlet, the framework will try to load the application context from a file named

[servlet-name]-servlet.xml located in the application's WebContent/WEB-INF directory. In this case our file will be

HelloWeb-servlet.xml.

Next, <servlet-mapping> tag indicates what URLs will be handled by the which DispatcherServlet. Here all the HTTP requests

ending with .jsp will be handled by the HelloWeb DispatcherServlet.

If you do not want to go with default filename as [servlet-name-servlet.xml and default location as WebContent/WEB-INF,you can customize this file name and location by adding the servlet listener ContextLoaderListener in your web.xml file asfollows:

<web-app...>

<!-------- DispatcherServlet definition goes here----->

....

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>/WEB-INF/HelloWeb-servlet.xml</param-value>

</context-param>

<listener>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 198/211 |

Page 199: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<listener-class>

org.springframework.web.context.ContextLoaderListener

</listener-class>

</listener>

</web-app>

Now, let us check the required configuration for HelloWeb-servlet.xml file, placed in your web application's WebContent/WEB-INF

directory:

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

xmlns:context="http://www.springframework.org/schema/context"

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

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:component-scan base-package="com.tutorialspoint" />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix" value="/WEB-INF/jsp/" />

<property name="suffix" value=".jsp" />

</bean>

</beans>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 199/211 |

Page 200: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Following are the important points about HelloWeb-servlet.xml file:

- The [servlet-name-servlet.xml file will be used to create the beans defined, overriding the definitions of any beans defined

with the same name in the global scope.

The <context:component-scan...> tag will be use to activate Spring MVC annotation scanning capability which allows tomake use of annotations like @Controller and @RequestMapping

- The InternalResourceViewResolver will have rules defined to resolve the view names. As per the above defined rule, a

logical view named hello is delegated to a view implementation located at /WEB-INF/jsp/hello.jsp .

Defining a Controller

DispatcherServlet delegates the request to the controllers to execute the functionality specific to it.

The @Controller annotation indicates that a particular class serves the role of a controller.

The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.

@Controller

@RequestMapping("/hello")

public class HelloController{

@RequestMapping(method = RequestMethod.GET)

public String printHello(ModelMap model) {

model.addAttribute("message", "Hello Spring MVC Framework!");

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 200/211 |

Page 201: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

return "hello";

}

}

- @RequestMapping(method = RequestMethod.GET) is used to declare the printHello() method as the controller's default

service method to handle HTTP GET request. You can define another method to handle any POST request at the same URL.

Creating JSP Views

- Spring MVC supports many types of views for different presentation technologies. These include - JSPs, HTML, PDF,

Excel worksheets, XML, Velocity templates, XSLT, JSON, Atom and RSS feeds, JasperReports etc. But most commonly we

use JSP templates written with JSTL. So let us write a simple hello view in /WEB-INF/hello/hello.jsp:

<html>

<head>

<title>Hello Spring MVC</title>

</head>

<body>

<h2>${message}</h2>

</body>

</html>

Here ${message} is the attribute which we have setup inside the Controller. You can have multiple attributes to

Be displayed inside your view.

Spring MVC Form Handling Example

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 201/211 |

Page 202: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

In this example show how to write a simple web based application which makes use of HTML forms using Spring Web MVC

framework. To start with it, let us have working STS IDE in place and follow the following steps to develop a Dynamic Form based

Web Application using Spring Web Framework:

Step 1: Create a Dynamic Web Project with a name SpringEmployeeApp and create a package com.dineshonjava.controller under

the src folder in the created project.

Step 2: Add below mentioned Spring 3.0 libraries and other libraries into the folder WebRoot/WEB-INF/lib.

commons-logging-1.1.1.jar

org.springframework.asm-3.0.0.jar

org.springframework.beans-3.0.0.jar

org.springframework.context-3.0.0.jar

org.springframework.core-3.0.0.jar

org.springframework.expression-3.0.0.jar

org.springframework.web.servlet-3.0.0.jar

org.springframework.web-3.0.0.jar

spring-web.3.0.0.jar

Step 3: Create a Java class EmployeeController and Employee under the com.dineshonjava.controller com.dineshonjava.bean

package respectively.

Step 4: Create Spring configuration files Web.xml and sdnext-servlet.xml under the WebRoot/WEB-INF/ folder.

Step 5: Create a sub-folder with a name views under the WebRoot/WEB-INF folder. Create a view file employeeForm.jsp and

employeeDetail.jsp under this sub-folder.

Step 6: The final step is to create the content of all the source and configuration files name sdnext-servlet.xml under the sub-folder

WebRoot/WEB-INF/config and export the application as explained below.

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 202/211 |

Page 203: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

Software versions used to run the sample code:

- Spring 3.0

- Java 1.6

- Tomcat 7

- JSTL 1.2

- STS Java EE IDE

- Web Application Structure:

Employee.java

view plainprint?

package com.dineshonjava.emp.bean;

/**

* @author Dinesh Rajput

*

*/

public class Employee {

private int empId;

private String name;

private Long salary;

private int age;

/**

* @return the empId

*/

public int getEmpId() {

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 203/211 |

Page 204: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

return empId;

}

/**

* @param empId the empId to set

*/

public void setEmpId(int empId) {

this.empId = empId;

}

/**

* @return the name

*/

public String getName() {

return name;

}

/**

* @param name the name to set

*/

public void setName(String name) {

this.name = name;

}

/**

* @return the salary

*/

public Long getSalary() {

return salary;

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 204/211 |

Page 205: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

}

/**

* @param salary the salary to set

*/

public void setSalary(Long salary) {

this.salary = salary;

}

/**

* @return the age

*/

public int getAge() {

return age;

}

/**

* @param age the age to set

*/

public void setAge(int age) {

this.age = age;

}

public String toString(){

return "Employee{ name-"+name+" age-"+age+" salary-"+salary+"}";

}

}

EmployeeController.java

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 205/211 |

Page 206: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

view plainprint?

package com.dineshonjava.emp.controller;

import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;

import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.servlet.ModelAndView;

import com.dineshonjava.emp.bean.Employee;

/**

* @author Dinesh Rajput

*

*/

@Controller

public class EmployeeController {

@RequestMapping(value = "/employee", method = RequestMethod.GET)

public ModelAndView employee() {

return new ModelAndView("employeeForm", "command", new Employee());

}

@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 206/211 |

Page 207: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

public String addEmployee(@ModelAttribute("SpringWeb")Employee employee, ModelMap model) {

model.addAttribute("name", employee.getName());

model.addAttribute("age", employee.getAge());

model.addAttribute("empId", employee.getEmpId());

model.addAttribute("salary", employee.getSalary());

return "employeeDetail";

}

}

Here the first service method employee(), we have passed a blank Employee object in the ModelAndView object with name

"command" because the spring framework expects an object with name "command" if you are using tags in your JSP file. So when

employee() method is called it returns employeeForm.jsp view.

Second service method addEmployee() will be called against a POST method on the sdnext/addEmployee URL. You will prepare

your model object based on the submitted information. Finally a "employeeDetail" view will be returned from the service method,

which will result in rendering employeeDetail.jsp

Following is the content of Spring Web configuration file web.xml

view plainprint?

<web-app id="WebApp_ID" version="3.0" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"

xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

<display-name>SpringMVCHelloWorld</display-name>

<welcome-file-list>

<welcome-file>/</welcome-file>

</welcome-file-list>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 207/211 |

Page 208: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<servlet>

<servlet-name>sdnext</servlet-name>

<servlet-class>

org.springframework.web.servlet.DispatcherServlet

</servlet-class>

<init-param>

<param-name>contextConfigLocation</param-name><param-value>/WEB-INF/config/sdnext-servlet.xml</param-value></init-par

am>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>sdnext</servlet-name>

<url-pattern>/</url-pattern>

</servlet-mapping>

</web-app>

Following is the content of another Spring Web configuration file sdnext-servlet.xml

view plainprint?

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

xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"

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

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

http://www.springframework.org/schema/mvc

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 208/211 |

Page 209: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<!-- Enable annotation driven controllers, validation etc... -->

<mvc:annotation-driven></mvc:annotation-driven>

<context:component-scan base-package="com.dineshonjava.emp.controller">

</context:component-scan>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver">

<property name="prefix" value="/WEB-INF/views/"></property>

<property name="suffix" value=".jsp"></property>

</bean>

</beans>

employeeForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<html>

<head>

<title>Spring MVC Form Handling</title>

</head>

&body>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 209/211 |

Page 210: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

<h2>

Employee Data Form</h2>

<form:form action="/sdnext/addEmployee" method="POST">

<table><tbody>

<tr>        <td><form:label path="empId">Employee :</form:label></td>      <td><form:input path="empId"></form:input></td>   

</tr>

<tr>      <td><form:label path="name">EmployeeName:/form:label></form:label></td>       <td><form:input

path="name"></form:input></td>    </tr>

<tr>       <td><form:label path="age">Employee Age:</form:label></td>       <td><form:input path="age"></form:input></td>    

</tr>

<tr>      <td><form:label path="salary">Employee Salary:</form:label></td>     <td><form:input

path="salary"></form:input></td>    </tr>

<tr>         <td colspan="2"><input type="submit" value="Submit"/>  </td>       </tr>

</tbody></table>

</form:form>

</body>

</html>

employeeDetail.jsp

view plainprint?

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<html>

<head>

<title>Spring MVC Form Handling</title>

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 210/211 |

Page 211: Spring Notes - TechnicalStack

This page was exported from - TechnicalStack Export date: Fri Jun 10 20:13:05 2022 / +0000 GMT

</head>

<body>

<h2>

Submitted Employee Information</h2>

<table border="1"><tbody>

<tr>     <td>Employee ID </td>      <td>${empId}</td>   </tr>

<tr>      <td>Employee Name</td>      <td>${name}</td>  </tr>

<tr>     <td>Employee Age</td>      <td>${age}</td>     </tr>

<tr>      <td>Employee Salary</td>       <td>${salary}</td> </tr>

</tbody></table>

</body>

</html>

Once you are done with creating source and configuration files, export your application. Right click on your application and use

Export-> WAR File option and save your SpringEmplyeeApp.war file in Tomcat's webapps folder.

Now start your Tomcat server and make sure you are able to access other web pages from webapps folder using a standard browser.

Now try a URL http://localhost:8080/sdnext/employee and you should see the following result if everything is fine with your Spring

Web Application:

After submitting required information click on submit button to submit the form. You should see the following result if everything is

fine with your Spring Web Application:

Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 211/211 |


Recommended