Spring-Interview-Preparation

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

When to use Spring.

Write less and archive more.

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

Spring Modules:-

  1. Spring Core Model:-
  2. Spring DAO (JDBC) Module:-
  3. Spring ORM Module:-
  4. Spring AOP Module:-
  5. Spring JEE Module:-
  6. Spring Web Module:-

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

What is the difference between IOC and 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.

Explain how Setter Injection With Primitive Values

 

 

 

Explain how Setter Injection With Objects

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

  1. By using inner beans –not recommended
  2. Using <ref /> element

Using <ref /> element–syntax -: <ref local/parent/bean=”id of collaborator bean”>

  • <ref local=”id value” />  –>will look in same xml file
  • <ref parent=”id value” />  –> will look in another xml file

Explain Spring Setter Injection, Dependency In The Form Of Collections ?

4 types of collections as dependency,available in spring are.

  1. Set
  2. List
  3. Map
  4. 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

How Spring Dependency Injection With Set Collection Property works ?

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

{

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

 

 

 

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

  1. java
  2. java
  3. xml

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

 

<!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;

 

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

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

}

 

}

 

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

 

files will be used..

  1. java
  2. java
  3. 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);

}

 

}

 

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

 

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

 

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

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

  1. java
  2. java
  3. xml

 

Directory structure:

 

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

}

}

 

}

 

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>

 

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

 

}

 

}

 

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)

{

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

 

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

 

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

 

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

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

 

}

 

}

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;

 

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>

 

<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

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

 

<bean id=”adminUser” class=”com..common.Customer”>

 

<!– java.util.Properties –>

<property name=”emails”>

<props>

<prop key=”admin”>admin@nospam.com</prop>

<prop key=”support”>support@nospam.com</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 responsible for containing and otherwise managing the aforementioned beans. The BeanFactory interface is the central IoC container interface 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.

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.
    1. FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(“F:/my workspace/springAppDemo/src/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.
    1. ApplicationContext context = new ClassPathXmlApplicationContext(“classpath:com/technicalstack/sdnext/springConfig/spring.xml”);

Using wildcard for claspath:

    1. ApplicationContext context = new ClassPathXmlApplicationContext(“classpath*:com/technicalstack/**/springConfig/spring.xml”);
    2. 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.
    1. 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:

 

  • 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

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 {

 

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

 

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

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

 

 

 

 

 

 

 

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

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

  1. 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.
  2. prototype: A new instance will be created every time the bean is requested.
  3. 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.
  4. session: A new bean will be created for each HTTP session by the container.
  5. 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:

 

@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..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.”)

public class AppConfig  {

}

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..AppConfig</param-value>

</context-param>

 

<!– 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..web.MvcConfig</param-value>

</init-param>

</servlet>

 

<!– 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 :

 

@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:

 

  1. Post initialization call back methods
  2. 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..task.DemoBean”

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

</beans>

 

 

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.

 

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

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

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

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.

 

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

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{

 

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

}

}

}

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

}

 

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

 

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

 

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.

 

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

Sometimes 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:

 

  1. ApplicationContextAware – to inject ApplicationContext object, example usage is to get the array of bean definition names.
  2. BeanFactoryAware – to inject BeanFactory object, example usage is to check scope of a bean.
  3. BeanNameAware – to know the bean name defined in the configuration file.
  4. ResourceLoaderAware – to inject ResourceLoader object, example usage is to get the input stream for a file in the classpath.
  5. ServletContextAware – to inject ServletContext object in MVC application, example usage is to read context parameters and attributes.
  6. 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

 

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 {

 

@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) {

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(

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

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]

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:

  1. Instantiate– First the spring container finds the bean’s definition from the XML file and instantiates the bean..
  2. Populate properties– Using the dependency injection, spring populates all of the properties as specified in the bean definition..
  3. Set Bean Name– If the bean implements BeanNameAware interface, spring passes the bean’s id to setBeanName() method.
  4. Set Bean factory– If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.
  5. Pre Initialization– Also called postprocess of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method.
  6. 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.
  7. Post Initialization– If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
  8. Ready to use– Now the bean is ready to use by the application.
  9. Destroy– If the bean implements DisposableBean , it will call the destroy() method .

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:
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. autodetect: Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.

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

  1. java
  2. java
  3. java
  4. 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;

}

 

}

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) {

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

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

 

 

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…

  1. java
  2. java
  3. java
  4. 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;

}

 

}

 

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) {

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

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>

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…

  1. java
  2. java
  3. java
  4. 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;

}

 

}

 

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

{

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

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

Files required…

  1. java
  2. java
  3. java
  4. 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;

}

 

}

 

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

{

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

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

 

<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..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(RequiredAnnotationBeanPostProcessor.java:156)

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)

… 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(){

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

</bean>

 

<!– Definition for spellChecker bean –>

<bean id=”spellChecker” class=”com..SpellChecker”>

</bean>

</beans>

 

Explain @Qualifier annotation with example?

@Qualifier means, which bean is qualify to autowired on a field. The qualifier annotation helps disambiguate bean references 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

private Person person;

}

And we have two bean definitions for Person class.

 

<bean id=”customer” class=”com..common.Customer” />

 

<bean id=”personA” class=”com..common.Person” >

<property name=”name” value=”lokesh” />

</bean>

 

<bean id=”personB” class=”com..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..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;

}

 

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

 

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..demo.service” />

<context:component-scan base-package=”com..demo.dao” />

<context:component-scan base-package=”com..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

{

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

}

 

 

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

}

}

 

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() {

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..demo.service.EmployeeManager;

 

public class TestSpringContext

{

public static void main(String[] args)

{

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

  • 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”);

}

}

 

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

{

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

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

}

}

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.

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

package com.technicalstack.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;

}

 

/**

* @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”);

}

 

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.technicalstack.sdnext.callbackLifecycle.tutorial;

 

public class Point

{

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) {

this.y = y;

}

}

 

package com.technicalstack.sdnext.callbackLifecycle.tutorial;

 

public class Point

{

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) {

this.y = y;

}

}

Following is the configuration file Spring.xml required for init and destroy methods.

Spring.xml

<bean id=triangle class=com.technicalstack.sdnext.callbackLifecycle.tutorial.Triangle init-method=”myInit” destroy-method=”cleanUp” autowire=”byName”>

</bean>

 

<bean id=pointA class=com.technicalstack.sdnext.callbackLifecycle.tutorial.Point>

<property name=”x” value=”0″></property>

<property name=”y” value=”0″></property>

</bean>

 

<bean id=pointB class=com.technicalstack.sdnext.callbackLifecycle.tutorial.Point>

<property name=”x” value=”-20″></property>

<property name=”y” value=”0″></property>

</bean>

 

<bean id=pointC class=com.technicalstack.sdnext.callbackLifecycle.tutorial.Point>

<property name=”x” value=”20″></property>

<property name=”y” value=”0″></property>

</bean>

</beans>

 

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.technicalstack.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();

}

 

}

 

package com.technicalstack.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:

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.technicalstack.sdnext.callbackLifecycle.tutorial.Triangle autowire=”byName”>

</bean>

 

<bean id=pointA class=com.technicalstack.sdnext.callbackLifecycle.tutorial.Point>

<property name=”x” value=”0″></property>

<property name=”y” value=”0″></property>

</bean>

<bean id=pointB class=com.technicalstack.sdnext.callbackLifecycle.tutorial.Point>

<property name=”x” value=”-20″></property>

<property name=”y” value=”0″></property>

</bean>

<bean id=pointC class=com.technicalstack.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

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.

 

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:

 

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

 

import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;

 

public class DemoServiceBasicUsageFixedDelay

{

@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..service.DemoServiceBasicUsageFixedDelay”></bean>

</beans>

Method 2) Task scheduling using cron expression in @Scheduled annotation

 

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

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

 

import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;

 

public class DemoServicePropertiesExample {

 

@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..service.DemoServicePropertiesExample”></bean>

</beans>

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

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

 

 

 

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:

 

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

 

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..dao.EmployeeDAO”>

<constructor-arg ref=”datasource”/>

</bean>

 

<!– Setter injection –>

<bean id=”employeeDAO” class=”com..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..EmployeeDAO”>

<constructor-arg index=”0″ value=”rest”/>

<constructor-arg index=”1″ value=”8080″/>

</bean>

 

<!– Type based constructor injection –>

<bean id=”employeeDAO” class=”com..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..dao.EmployeeDAO”>

<property name=”datasource”>

<ref bean=”datasource”></ref>

<value>datasource</value>

</property>

</bean>

 

<!– Shorter/shortcut version –>

<bean id=”employeeDAO” class=”com..dao.EmployeeDAO”>

<property name=”datasource”  ref=”datasource” value=”datasource”>

</bean>

7) Reuse bean definitions as much as possible

 

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.

 

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

 

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”

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.

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 :

 

  1. CommonAnnotationBeanPostProcessor :

Recognizes and processes the JSR 250 common annotations (@PostConstruct, @PreDestroy, @Resource)

 

  1. AutowiredAnnotationBeanPostProcessor :

Recognizes the Autowired related annotations (@Autowired, @Value, @Inject, @Qualifier, etc)

 

  1. RequiredAnnotationBeanPostProcessor :

Recognizes the @Required annotation

 

  1. 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 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&gt; 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..beans;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

 

@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

 

package com..beans;

 

import org.springframework.stereotype.Component;

 

@Component

public class BeanB {

public BeanB(){

System.out.println(“Creating bean BeanB”);

}

}

 

//Bean C

 

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

 

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

 

  1. a) Define only bean tags

 

<bean id=”beanA” class=”com..beans.BeanA”></bean>

<bean id=”beanB” class=”com..beans.BeanB”></bean>

<bean id=”beanC” class=”com..beans.BeanC”></bean>

 

Output:

 

Creating bean BeanA

Creating bean BeanB

Creating bean BeanC

In this case, all 3 beans are created and no dependency in injected in BeanA because we didn’t used any property/ref attributes.

 

  1. b) Define bean tags and property ref attributes

 

<bean id=”beanA” class=”com..beans.BeanA”>

<property name=”beanB” ref=”beanB”></property>

<property name=”beanC” ref=”beanC”></property>

</bean>

<bean id=”beanB” class=”com..beans.BeanB”></bean>

<bean id=”beanC” class=”com..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.

 

  1. c) Using only <context:annotation-config />

 

<context:annotation-config />

 

//No Output

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.

 

  1. d) Using <context:annotation-config /> with bean declarations

 

<context:annotation-config />

<bean id=”beanA” class=”com..beans.BeanA”></bean>

<bean id=”beanB” class=”com..beans.BeanB”></bean>

<bean id=”beanC” class=”com..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.

 

  1. e) Using only <context:component-scan />

 

<context:component-scan base-package=”com..beans” />

 

Output:

 

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

 

  1. f) Using both <context:component-scan /> and <context:annotation-config />

 

<context:annotation-config />

<context:component-scan base-package=”com..beans” />

<bean id=”beanA” class=”com..beans.BeanA”></bean>

<bean id=”beanB” class=”com..beans.BeanB”></bean>

<bean id=”beanC” class=”com..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 !!

 

 

Spring JdbcTemplate

 

Spring JdbcTemplate internally uses JDBC api, but eliminates a lot of problems of JDBC API.

 

Problems of JDBC API

 

  1. We need to write a lot of code before and after executing the query, such as creating connection, statement, closing resultset, connection etc.
  2. We need to perform exception handling code on the database logic.
  3. We need to handle transaction.
  4. Repetition of all these codes from one to another database logic is a time consuming task.
  5. 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:

 

  1. JdbcTemplate
  2. NamedParameterJdbcTemplate
  3. SimpleJdbcTemplate
  4. 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 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

}

 

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

}

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

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

 

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

 

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)

);

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;

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

}

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

<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) {

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.

 

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;

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

}

 

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”

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.

 

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

 

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;

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

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”

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>

 

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.

 

  • 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;

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

}

 

}

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>

 

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

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:

 

  1. 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.
  2. Easy to test: Spring’s IoC approach makes it easy to test the application.
  3. Better exception handling: Spring framework provides its own API for exception handling with ORM framework.
  4. 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.

 

  • 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

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

 

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

“-//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;

}

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

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

 

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

 

 

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

 

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 =

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

 

 

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

<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 as follows:

 

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

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

 

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 to make 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!”);

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

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.technicalstack.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.technicalstack.controller com.technicalstack.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.

 

Software versions used to run the sample code:

 

  1. Spring 3.0
  2. Java 1.6
  3. Tomcat 7
  4. JSTL 1.2
  5. STS Java EE IDE
  6. Web Application Structure:

 

Employee.java

view plainprint?

package com.technicalstack.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() {

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;

}

/**

* @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

view plainprint?

package com.technicalstack.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.technicalstack.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)

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>

 

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

<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

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

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

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

 

   

Share :Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Comments are closed