This is 14 of 16 parts of tutorial series

Tutorial Content: Spring tutorial for beginners

    Introduction to spring framework Spring interview questions Dependency injection(ioc) in spring Spring hello world example in eclipse Spring java based configuaration Dependency injection via setter method in spring Dependency injection via constructor in spring Spring Bean scopes with examples Initializing collections in spring Beans Autowiring in spring Inheritance in Spring Spring ApplicationContext Spring lifetime callbacks BeanPostProcessors in Spring Annotation based Configuration in spring Spring AOP tutorial
BeanPostProcessors interface provides methods that you can implement to have your own instantiation logic.Also you can write your own logic after spring IOC finishes instantiating, configuring, and initializing a bean by plugging in one or more BeanPostProcessor implementations.

You can configure multiple BeanPostProcessors and also can decide the order in which they will run relative to each other by setting order property but foe that BeanPostProcessors  have to implement ordered interface.

Extension of BeanPostProcessor is BeanFactoryPostProcessor interface which allows direct modification of bean definitions before a bean is instantiated

An ApplicationContext will automatically register and process a bean that implements either of these interfaces, but a BeanFactory would have to have a BeanPostProcessor or BeanFactoryPostProcessor registered with it programatically.

Example:

For configuring spring in your eclipse ide please refer  hello world example

1.Country.java:

This is simple pojo class having some attributes so here country has name.
Create Country.java under package org.arpit.javapostsforlearning.Copy following content into Country.java.

package org.arpit.javapostsforlearning;

public class Country {

 String countryName ;
 
 public String getCountryName() {
  return countryName;
 }
 
 
 public void setCountryName(String countryName) {
  this.countryName = countryName;
 }

 public void init()
 {
  System.out.println("In init block of country");
 }

 public void destroy()
 {
  System.out.println("In destroy block of country");
 }
}

2.InitCapitalPostProcessor.java:

This is simple pojo class implementing BeanPostProcessor interface.
Create InitCapitalPostProcessor.java under package org.arpit.javapostsforlearning.Copy following content into InitCapitalPostProcessor.java.

package org.arpit.javapostsforlearning;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class InitCapitalPostProcessor implements BeanPostProcessor{

 public Object postProcessAfterInitialization(Object bean, String beanName)
   throws BeansException {
  System.out.println("AfterInitialization : " + beanName);
       return bean;  // you can return any other object as well
 }

 public Object postProcessBeforeInitialization(Object bean, String beanName)
   throws BeansException {
  
       System.out.println("BeforeInitialization : " + beanName);
       return bean;  // you can return any other object as well
 }

}

 Here we are writing very simple logic but you can write quite complex logic  in above functions.You can note that you have object of bean class here so you can change it in whatever way you want and can return same or different object.

3.BeanPostProcessorExampleMain.java

This class contains main function.Create BeanPostProcessorExampleMain.java under package org.arpit.javapostsforlearning.Copy following content into BeanPostProcessorExampleMain.java
package org.arpit.javapostsforlearning;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanPostProcessorExampleMain{

 public static void main(String[] args) {

  AbstractApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
  Country countryObj = (Country) appContext.getBean("country");
  System.out.println("Country Name: "+countryObj.getCountryName());
  appContext.registerShutdownHook();
 }
}
Here you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensures a graceful shutdown and calls the relevant destroy methods.

4.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:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 <bean id="country" class="org.arpit.javapostsforlearning.Country" init-method="init" destroy-method="destroy">
 <property name="countryName" value="India"/>
 </bean>
      <bean class="org.arpit.javapostsforlearning.InitCapitalPostProcessor"/> 
 </beans>

5.Run it

When you will run above application,you will get following as output.

BeforeInitialization : country
In init block of country
AfterInitialization : country
Country Name: India
In destroy block of country

 

This is 13 of 16 parts of tutorial series

Tutorial Content:

    Introduction to spring framework Spring interview questions Dependency injection(ioc) in spring Spring hello world example in eclipse Spring java based configuaration Dependency injection via setter method in spring Dependency injection via constructor in spring Spring Bean scopes with examples Initializing collections in spring Beans Autowiring in spring Inheritance in Spring Spring ApplicationContext Spring lifetime callbacks BeanPostProcessors in Spring Annotation based Configuration in spring Spring AOP tutorial
The Spring Framework provides several callback interfaces to change the behavior of your bean in the container; they include InitializingBean and DisposableBean.

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.

Initialization callbacks:

Implementing the org.springframework.beans.factory.InitializingBean interface allows a bean to perform initialization work after all necessary properties on the bean have been set by the container. The InitializingBean interface specifies exactly one method:

void afterPropertiesSet() throws Exception; 


Generally, the use of the InitializingBean interface can be avoided and is actually discouraged since it unnecessarily couples the code to Spring.You have to use  afterPropertiesSet(),you can not change name of method.There is alternative for this i.e. XML-based configuration metadata.This is done using the 'init-method' attribute of <bean> tag.It provides flexibility of changing method name.

<bean id="countryBean" class="org.arpit.javapostsforlearning.Country" init-method="init"/>

public class Country{
    
    public void init() {
        // do some initialization work
    }
} 
...is exactly the same as...

<bean id="countryBean" class="org.arpit.javapostsforlearning.Country"/>

public class Country implements InitializingBean {
    
    public void afterPropertiesSet() {
        // do some initialization work
    }
} 
... but does not couple the code to Spring.

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 a single method:

void destroy() throws Exception; 

 Generally, the use of the DisposableBean interface can be avoided and is actually discouraged since it unnecessarily couples the code to Spring.You have to use  destroy(),you can not change name of method.There is alternative for this i.e. XML-based configuration metadata.This is done using the 'destroy-method' attribute of <bean> tag.It provides flexibility of changing method name.

<bean id="countryBean" class="org.arpit.javapostsforlearning.Country" init-method="destroy"/>

public class Country{
    
    public void destroy() {
        // do some destruction work(like releasing pooled connections)
    }
} 
...is exactly the same as...

<bean id="countryBean" class="org.arpit.javapostsforlearning.Country"/>

public class Country implements DisposableBean{
    
    public void destroy() {
        // do some destruction work(like releasing pooled connections)   
 }
} 
... but does not couple the code to Spring.

Example:

For configuring spring in your eclipse ide please refer  hello world example

1.Country.java:

This is simple pojo class having some attributes so here country has name.
Create Country.java under package org.arpit.javapostsforlearning.Copy following content into Country.java.

package org.arpit.javapostsforlearning;

public class Country {

 String countryName ;
 
 public String getCountryName() {
  return countryName;
 }
 
 
 public void setCountryName(String countryName) {
  this.countryName = countryName;
 }

 public void init()
 {
  System.out.println("In init block of country");
 }

 public void destroy()
 {
  System.out.println("In destroy block of country");
 }
}

2.LifetimeCallbacksMain.java

This class contains main function.Create LifetimeCallbacksMain.java under package org.arpit.javapostsforlearning.Copy following content into LifetimeCallbacksMain.java
package org.arpit.javapostsforlearning;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class LifetimeCallbacksMain{

 public static void main(String[] args) {

  AbstractApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
  Country countryObj = (Country) appContext.getBean("country");
  System.out.println("Country Name: "+countryObj.getCountryName());
  appContext.registerShutdownHook();
 }
}
Here you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensures a graceful shutdown and calls the relevant destroy methods.

3.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:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 <bean id="country" class="org.arpit.javapostsforlearning.Country" init-method="init" destroy-method="destroy">
 <property name="countryName" value="India"/>
 </bean>
  
</beans>

4.Run it

When you will run above application,you will get following as output.


In init block of country
Country Name: India
In destroy block of country

Default Initialization and destroy method:

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:

<?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:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
 default-init-method="init"
 default-destroy-method="destroy"
 >
 
 <bean id="country" class="org.arpit.javapostsforlearning.Country">
 <property name="countryName" value="India"/>
 </bean>
  
</beans>





 

This is 12 of 16 parts of tutorial series

Tutorial Content: Spring tutorial for beginners

    Introduction to spring framework Spring interview questions Dependency injection(ioc) in spring Spring hello world example in eclipse Spring java based configuaration Dependency injection via setter method in spring Dependency injection via constructor in spring Spring Bean scopes with examples Initializing collections in spring Beans Autowiring in spring Inheritance in Spring Spring ApplicationContext Spring lifetime callbacks BeanPostProcessors in Spring Annotation based Configuration in spring Spring AOP tutorial
In this tutorial we will learn about what is ApplicationContext and how we can access it.

ApplicationContext:

ApplicationContext is an central interface for providing configuration information to an application.

An ApplicationContext provides the following functionalities:
  • Bean factory methods, inherited from ListableBeanFactory. This avoids the need for applications to use singletons.
  • The ability to resolve messages, supporting internationalization. Inherited from the MessageSource interface.
  • The ability to load file resources in a generic fashion. Inherited from the ResourceLoader interface.
  • The ability to publish events. Implementations must provide a means of registering event listeners.
  • Inheritance from a parent context. Definitions in a descendant context will always take priority. This means, for example, that a single parent context can be used by an entire web application, while each servlet has its own child context that is independent of that of any other servlet.

 ApplicationContext vs BeanFactory:

We can get our bean from both by applying getBean method.BeanFactory is subset of ApplicationContext and provides less functionalities.So if we want to use full functionalities then we go for ApplicationContext.

Getting ApplicationContext in Bean Class:

To get access to ApplicationContext we should implement ApplicationContextAware interface in the respective java bean. 

ApplicationContextAware  Interface:

 It has a method,
public void setApplicationContext(ApplicationContext applicationContext)

            throws BeansException
The ApplicationContext implementation which we are using in our application will invoke this method and pass the concrete object for AppplicationContext. Using this we can get access to all the configuration information.

Implementing ApplicationContextAware interface makes sense for example when an object requires access to a set of collaborating beans. Note that configuration via bean references is preferable to implementing this interface just for bean lookup purposes.

This interface can also be implemented if an object needs access to file resources, i.e. wants to call getResource, wants to publish an application event, or requires access to the MessageSource. However, it is preferable to implement the more specific ResourceLoaderAware, ApplicationEventPublisherAware or MessageSourceAware interface in such a specific scenario.

Example:

For configuring spring in your eclipse ide please refer  hello world example

1.Country.java:

This is simple pojo class having some attributes so here country has name and object of Capital class.
Create Country.java under package org.arpit.javapostsforlearning.Copy following content into Country.java.

package org.arpit.javapostsforlearning;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class Country implements ApplicationContextAware{

 String countryName ;
 ApplicationContext applicationContext;
 Capital capital;
 public String getCountryName() {
  return countryName;
 }
 
 
 public void setCountryName(String countryName) {
  this.countryName = countryName;
 }


 public void setApplicationContext(ApplicationContext applicationContext)
   throws BeansException {
  this.applicationContext=applicationContext;
 }
 
 public String getCapitalName(String capitalBeanName)
 {
  capital=(Capital) applicationContext.getBean(capitalBeanName);
  String capitalName=capital.getCapitalName();
  return capitalName;
 }
}

2.Capital.java

This is also simple pojo class having one attribute called "capitalName".
Create Capital.java under package org.arpit.javapostsforlearning.java.Above Country class contains object of this class.Copy following content into Capital.java

package org.arpit.javapostsforlearning;

public class Capital {

    String capitalName;

    public String getCapitalName() {
        return capitalName;
    }

    public void setCapitalName(String capitalName) {
        this.capitalName = capitalName;
    }
}

3.ApplicationContextMain.java

This class contains main function.Create ApplicationContextMain.java under package org.arpit.javapostsforlearning.Copy following content into ApplicationContextMain.java
 package org.arpit.javapostsforlearning;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ApplicationContextMain{

 public static void main(String[] args) {

  ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
  Country countryObj = (Country) appContext.getBean("country");
  System.out.println("Capital Name:"+countryObj.getCapitalName("capital"));
 }
}
You can note here that we have used ClassPathXmlApplicationContext for getting bean here.There are various ways for getting beans.In hello world example we have used XmlBeanFactory for getting beans.

4.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:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 <bean id="country" class="org.arpit.javapostsforlearning.Country" >
 <property name="countryName" value="India"/>
 </bean>
 
 <bean id="capital" class="org.arpit.javapostsforlearning.Capital" >
 <property name="capitalName" value="Delhi"/>
 </bean>
</beans>
As you can see, there is no connection between above two beans in this XML file.We are getting object of country class with help of getBean method and then passing id of  capital class to getCapitalName method of country class.In getCapital method,we have ApplicationContext object which is initialized by setApplicationContext method by spring container ,so with help of ApplicationContext object,we are calling getBean method for initializing capital object and getting capitalName from that object.

5.Run it

When you will run above application,you will get following as output.
India's Capital Name:Delhi

Source code:


In next post,we will see spring lifetime callbacks.

 



This is 11 of 16 parts of tutorial series

Tutorial Content: Spring tutorial for beginners

    Introduction to spring framework Spring interview questions Dependency injection(ioc) in spring Spring hello world example in eclipse Spring java based configuaration Dependency injection via setter method in spring Dependency injection via constructor in spring Spring Bean scopes with examples Initializing collections in spring Beans Autowiring in spring Inheritance in Spring Spring ApplicationContext Spring lifetime callbacks BeanPostProcessors in Spring Annotation based Configuration in spring Spring AOP tutorial
In spring,inheritance is supported for reusing already written bean,so that beans can share common attributes and methods among them.

child bean will have all attributes and methods of parent bean,also child bean can override parent bean's attributes or methods.

For configuring spring in your eclipse ide please refer  hello world example

1.Person.java:

This is simple pojo class having some attributes so here preson has name .
Create Person.java under package org.arpit.javapostsforlearning.Copy following content into Person.java.

package org.arpit.javapostsforlearning;

public class Person {

 String name;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
 
}

2.Employee.java

This is also simple pojo class having one attribute called "employeeNumber".
Create Employee.java under package org.arpit.javapostsforlearning.java..Copy following content into Employee.java

package org.arpit.javapostsforlearning;

public class Employee extends Person{
 
 int employeeNumber;

 public int getEmployeeNumber() {
  return employeeNumber;
 }

 public void setEmployeeNumber(int employeeNumber) {
  this.employeeNumber = employeeNumber;
 }
 
}

3.InheritanceInSpringMain.java

This class contains main function.Create InheritanceInSpring.java under package org.arpit.javapostsforlearning.Copy following content into InheritanceInSpring.java

package org.arpit.javapostsforlearning;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class InheritenceInSpringMain {

 public static void main(String[] args) {
  ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
  Employee emp=(Employee) appContext.getBean("employeeBean");
  System.out.println("Employee name:"+emp.getName());
  System.out.println("Employee number:"+emp.getEmployeeNumber());
 }
}
You can note here that we have used ClassPathXmlApplicationContext for getting bean here.There are various ways for getting beans.In hello world example we have used XmlBeanFactory for getting beans.

4.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:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 <bean id="personBean" class="org.arpit.javapostsforlearning.Person">
  <property name="name" value="Arpit"/>
 </bean>
 <bean id="employeeBean" class="org.arpit.javapostsforlearning.Employee" parent="personBean">
  <property name="employeeNumber" value="178230" />
 </bean>
</beans>

Here We have declared two beans with corresponding ids.
1.Class Person with id as "PersonBean"
2.Class Employee with id as "EmployeeBean"
We have used  parent property of to show that Person is parent class of Employee.

<bean id="employeeBean" class="org.arpit.javapostsforlearning.Employee" parent="id or name of parent bean">

5.Run it

When you will run above application,you will get following as output.

Employee name:Arpit
Employee number:178230

Source code:

In next post,we will see spring applicationContext.

This is 10 of 16 parts of tutorial series

Tutorial Content: Spring tutorial for beginners

    Introduction to spring framework Spring interview questions Dependency injection(ioc) in spring Spring hello world example in eclipse Spring java based configuaration Dependency injection via setter method in spring Dependency injection via constructor in spring Spring Bean scopes with examples Initializing collections in spring Beans Autowiring in spring Inheritance in Spring Spring ApplicationContext Spring lifetime callbacks BeanPostProcessors in Spring Annotation based Configuration in spring Spring AOP tutorial
You have learnt how to declare beans using the <bean> element and inject <bean> with using <constructor-arg> and <property> elements in XML configuration file.

In Spring framework, you can wire beans automatically with auto-wiring feature. To enable it, just define the “autowire” attribute in <bean>.The Spring container can autowire relationships between collaborating beans without using <constructor-arg> and <property> elements which helps cut down on the amount of XML configuration

<bean id="countryBean" class="org.arpit.javapostsforlearning.Country" autowire="byName">

Autowiring modes:

There are following autowiring modes which can be used to instruct Spring container to use autowiring for dependency injection.

no:

Default, no auto wiring, set it manually via “ref” attribute as we have done in dependency injection via settor method post.

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 and it tries to match it with name of bean in xml configuration file.

byType:

Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exists, a fatal exception is thrown.

contructor:

byType mode in constructor argument.

autodetect:

Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.

Example:

I am taking example of autowire "byName" here.It will be almost same as Dependency injection via setter method with some changes in XML configuration file.

1.Country.java:

This is simple pojo class having some attributes so here country has name and object of Capital class.
Create Country.java under package org.arpit.javapostsforlearning.Copy following content into Country.java.

package org.arpit.javapostsforlearning;

public class Country {

    String countryName;
    Capital capital;
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    public Capital getCapital() {
        return capital;
    }
    public void setCapital(Capital capital) {
        this.capital = capital;
    }
}

2.Capital.java

This is also simple pojo class having one attribute called "capitalName".
Create Capital.java under package org.arpit.javapostsforlearning.java.Above Country class contains object of this class.Copy following content into Capital.java
package org.arpit.javapostsforlearning;

public class Capital {

    String capitalName;

    public String getCapitalName() {
        return capitalName;
    }

    public void setCapitalName(String capitalName) {
        this.capitalName = capitalName;
    }
}

3.BeanAutowirngByNameMain.java

This class contains main function.Create BeanAutowiringByNameMain.java under package org.arpit.javapostsforlearning.Copy following content into BeanAutowiringByNameMain.java

package org.arpit.javapostsforlearning;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanAutowiringByNameMain{

    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");

        Country countryObj = (Country) appContext.getBean("country");
        String countryName=countryObj.getCountryName();
        String capitalName=countryObj.getCapital().getCapitalName();
        System.out.println(capitalName+" is capital of "+countryName);
       
    }
}
You can note here that we have used ClassPathXmlApplicationContext for getting bean here.There are various ways for getting beans.In hello world example we have used XmlBeanFactory for getting beans.

4.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:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 <bean id="country" class="org.arpit.javapostsforlearning.Country" autowire="byName">
  <property name="countryName" value="India"/>
 </bean>
 <bean id="capital" class="org.arpit.javapostsforlearning.Capital">
  <property name="capitalName" value="Delhi" />
 </bean>
</beans>

Here in <bean>,we have used autowire attribute and set it to "byName".So now spring container will match "capital" reference in Country class with id or name of other beans in XML configuration file. So here you can see we have bean with id as "capital"

5.Run it

When you will run above application,you will get following as output.

Delhi is capital of India

Limitations of Autowiring :

  • OverRiding possibilities:You can still define dependencies using <property> or <constructor-args> tag which will always override autowiring.
  • Primitive data type:you have to define primitive data type like String or Interger using <property> or <constructor-args> tag.You can not autowire them.
  • Confusing Nature:If you have lot of dependency in program,then its very hard to find out using autowire attribute of bean.

Source code:

In next post,we will see inheritance in spring.

This is 9 of 16 parts of tutorial series

Tutorial Content: Spring tutorial for beginners

    Introduction to spring framework Spring interview questions Dependency injection(ioc) in spring Spring hello world example in eclipse Spring java based configuaration Dependency injection via setter method in spring Dependency injection via constructor in spring Spring Bean scopes with examples Initializing collections in spring Beans Autowiring in spring Inheritance in Spring Spring ApplicationContext Spring lifetime callbacks BeanPostProcessors in Spring Annotation based Configuration in spring Spring AOP tutorial
In previous posts we have seen how to initialize any string or reference via property's value tag or ref tag.In this post we will see how to initialize any collections in spring.
For configuring spring in your eclipse ide please refer  hello world example

1.Country.java:

This is simple pojo class having some attributes so here country has name and list of states.
Create Country.java under package org.arpit.javapostsforlearning.Copy following content into Country.java.

package org.arpit.javapostsforlearning;

import java.util.List;

public class Country {

    String countryName;
    List<String> listOfStates;
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    public List<String> getListOfStates() {
        return listOfStates;
    }
    public void setListOfStates(List<String> listOfStates) {
        this.listOfStates = listOfStates;
    }
   
    public void printListOfStates()
    {
        System.out.println("Some of states in india are:");
        for(String state:listOfStates)
        {
            System.out.println(state);
        }
    }
}

2.InitializingCollectionsMain.java

This class contains main function.Create InitializingCollectionsMain.java under package org.arpit.javapostsforlearning.Copy following content into InitializingCollectionsMain.java
package org.arpit.javapostsforlearning;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class InitializingCollectionsMain{

    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        Country countryObj = (Country) appContext.getBean("CountryBean");
        countryObj.printListOfStates();
    }
}

You can note here that we have used ClassPathXmlApplicationContext for getting bean here.There are various ways for getting beans.In hello world example we have used XmlBeanFactory for getting beans.

3.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:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 <bean id="CountryBean" class="org.arpit.javapostsforlearning.Country">
  <property name="listOfStates">
   <list>
    <value>Maharastra</value>
    <value>Madhya Pradesh</value>
    <value>Rajasthan</value>
   </list>

  </property>
 </bean>

</beans>

here for initializing collectios(list) i.e. listofStates attribute of country class, we have used <list> tag.
In <list> tag ,you can have <value> tag or <ref> tag for adding values in list.

4.Run it

When you will run above application,you will get following as output.
Some of states in india are:
Maharastra
Madhya Pradesh
Rajasthan

Source code:

In next post,we will see beans autowiring in spring.

This is 8 of 16 parts of tutorial series

Tutorial Content: Spring tutorial for beginners

    Introduction to spring framework Spring interview questions Dependency injection(ioc) in spring Spring hello world example in eclipse Spring java based configuaration Dependency injection via setter method in spring Dependency injection via constructor in spring Spring Bean scopes with examples Initializing collections in spring Beans Autowiring in spring Inheritance in Spring Spring ApplicationContext Spring lifetime callbacks BeanPostProcessors in Spring Annotation based Configuration in spring Spring AOP tutorial
In Spring, bean scope is used to decide which type of bean instance should be return from Spring container back to the caller.
There are 5 types of bean scopes supported in spring
  1. singleton – Scopes a single bean definition to a single object instance per Spring IoC container.
  2. prototype – Return a new bean instance each time when requested
  3. request – Return a single bean instance per HTTP request.
  4. session – Return a single bean instance per HTTP session.
  5. globalSession – Return a single bean instance per global HTTP session. 
In many cases,spring's core scopes i.e.singleton and prototype are used.By default scope of beans is singleton.
Here we will see singleton and prototype scopes in more details.

Singleton bean scope:

Example:

For configuring spring in your eclipse ide please refer  hello world example

1.Country.java:

This is simple pojo class having some attributes so here country has name.
Create Country.java under package org.arpit.javapostsforlearning.Copy following content into Country.java.

package org.arpit.javapostsforlearning;

public class Country {

 String countryName;
 
 public String getCountryName() {
  return countryName;
 }
 
 
 public void setCountryName(String countryName) {
  this.countryName = countryName;
 }
 
}


2.ScopesInSpringMain.java

This class contains main function.Create ScopesInSpringMain.java under package org.arpit.javapostsforlearning.Copy following content into ScopesInSpringMain.java
package org.arpit.javapostsforlearning;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ScopesInSpringMain{

 public static void main(String[] args) {
  
  ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
  Country countryObj1 = (Country) appContext.getBean("country");
  countryObj1.setCountryName("India");
  System.out.println("Country Name:"+countryObj1.getCountryName());
  
  //getBean called second time
  Country countryObj2 = (Country) appContext.getBean("country");
  System.out.println("Country Name:"+countryObj2.getCountryName());
 }
}

3.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:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 <bean id="country" class="org.arpit.javapostsforlearning.Country">
 </bean>
</beans>

4.Run it

When you will run above application,you will get following as output.

Country Name:India
Country Name:India

When We firstly called getBean and retrieved country object and set countryName to "india" and when second time we called getBean method it did nothing but returned same object with countryName as "india".

Prototype bean scope:



 Now we will make change in above xml configuration file.We will add scope attribute in <bean> tag and set it to "prototype" and then run it again

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:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 <bean id="country" class="org.arpit.javapostsforlearning.Country" scope="prototype">
 </bean>
</beans>

Run it again:

When you will run above application,you will get following as output.
Country Name:India
Country Name:null

When We firstly called getBean and retrieved country object and set countryName to "india" and when second time we called getBean method it returned new object with countryName as "null".

Source code:

For singleton example:


For prototype example:

In next post,we will see initializing collections in spring.

This is 7 of 16 parts of tutorial series

Tutorial Content: Spring tutorial for beginners

    Introduction to spring framework Spring interview questions Dependency injection(ioc) in spring Spring hello world example in eclipse Spring java based configuaration Dependency injection via setter method in spring Dependency injection via constructor in spring Spring Bean scopes with examples Initializing collections in spring Beans Autowiring in spring Inheritance in Spring Spring ApplicationContext Spring lifetime callbacks BeanPostProcessors in Spring Annotation based Configuration in spring Spring AOP tutorial
As the name implies, using constructor spring container will inject the dependencies.
For configuring spring in your eclipse ide please refer  hello world example

1.Country.java:

This is simple pojo class having some attributes so here country has name and object of Capital class.
Create Country.java under package org.arpit.javapostsforlearning.Copy following content into Country.java.
package org.arpit.javapostsforlearning;

public class Country {

    String countryName;
    Capital capital;
   
    public Country(String countryName, Capital capital) {
        super();
        this.countryName = countryName;
        this.capital = capital;
    }
    public String getCountryName() {
        return countryName;
    }
   
    public Capital getCapital() {
        return capital;
    }
   
}

2.Capital.java

This is also simple pojo class having one attribute called "capitalName".
Create Capital.java under package org.arpit.javapostsforlearning.java.Above Country class contains object of this class.Copy following content into Capital.java
package org.arpit.javapostsforlearning;

public class Capital {

    String capitalName;

    public String getCapitalName() {
        return capitalName;
    }

    public void setCapitalName(String capitalName) {
        this.capitalName = capitalName;
    }
}

3.ConstructorDIMain.java

This class contains main function.Create ConstructorDIMain.java under package org.arpit.javapostsforlearning.Copy following content into ConstructorDIMain.java

 package org.arpit.javapostsforlearning;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;

public class ConstructorDIMain{

    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");

        Country countryObj = (Country) appContext.getBean("CountryBean");
        String countryName=countryObj.getCountryName();
        String capitalName=countryObj.getCapital().getCapitalName();
        System.out.println(capitalName+" is capital of "+countryName);
       
    }
}
You can note here that we have used ClassPathXmlApplicationContext for getting bean here.There are various ways for getting beans.In hello world example we have used XmlBeanFactory for getting beans.

4.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:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 <bean id="CountryBean" class="org.arpit.javapostsforlearning.Country">
  <constructor-arg index="0" type="java.lang.String" value="India" />
  <constructor-arg index="1" ref="CaptialBean" />
 </bean>
 <bean id="CaptialBean" class="org.arpit.javapostsforlearning.Capital">
  <property name="capitalName" value="Delhi" />
 </bean>
</beans>
Here We have declared two beans with corresponding ids.
1.Class Country with id as "CountryBean"
2.Class Capital with id as "CapitalBean"
constructor-arg tag is used for providing argument to bean' s constructor.type is for declaring data types and index defines position in constructor's argument.
In above xml,Two arguments are passed.
1. India as string
2.CapitalBean 's reference
Property's value tag is for assigning value to corresponding attribute. so In above xml file,we have assigned capitalName attribute of Capital class with value as Delhi
<property name="Name Of Attribute" value="Value Of attribute to be assigned"/>
Property's ref tag is for assigning reference to corresponding attribute. so In above xml file,we have assigned reference of Capital class to capital attribute of Country class.
<property name="Name Of Attribute" value="id of referencing bean"/>

5.Run it

When you will run above application,you will get following as output.

Delhi is capital of India

Source code:

In next post,we will see spring bean scopes

This is 6 of 16 parts of tutorial series

Tutorial Content: Spring tutorial for beginners

    Introduction to spring framework Spring interview questions Dependency injection(ioc) in spring Spring hello world example in eclipse Spring java based configuaration Dependency injection via setter method in spring Dependency injection via constructor in spring Spring Bean scopes with examples Initializing collections in spring Beans Autowiring in spring Inheritance in Spring Spring ApplicationContext Spring lifetime callbacks BeanPostProcessors in Spring Annotation based Configuration in spring Spring AOP tutorial
As the name implies, using setter method spring container will inject the dependencies.This technique is considered as the best approach for dependency injection.
For configuring spring in your eclipse ide please refer  hello world example

1.Country.java:

This is simple pojo class having some attributes so here country has name and object of Capital class.
Create Country.java under package org.arpit.javapostsforlearning.Copy following content into Country.java.
package org.arpit.javapostsforlearning;

public class Country {

    String countryName;
    Capital capital;
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    public Capital getCapital() {
        return capital;
    }
    public void setCapital(Capital capital) {
        this.capital = capital;
    }
}

2.Capital.java

This is also simple pojo class having one attribute called "capitalName".
Create Capital.java under package org.arpit.javapostsforlearning.java.Above Country class contains object of this class.Copy following content into Capital.java
package org.arpit.javapostsforlearning;

public class Capital {

    String capitalName;

    public String getCapitalName() {
        return capitalName;
    }

    public void setCapitalName(String capitalName) {
        this.capitalName = capitalName;
    }
}

3.SetterMehtodMain.java

This class contains main function.Create SetterMethodMain.java under package org.arpit.javapostsforlearning.Copy following content into SetterMethodMain.java
 package org.arpit.javapostsforlearning;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;

public class SetterInjectionMain {

    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");

        Country countryObj = (Country) appContext.getBean("CountryBean");
        String countryName=countryObj.getCountryName();
        String capitalName=countryObj.getCapital().getCapitalName();
        System.out.println(capitalName+" is capital of "+countryName);
       
    }
}
You can note here that we have used ClassPathXmlApplicationContext for getting bean here.There are various ways for getting beans.In hello world example we have used XmlBeanFactory for getting beans.

4.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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

  <bean id="CountryBean" class="org.arpit.javapostsforlearning.Country">
      <property name="countryName" value="India"/>
      <property name="capital" ref="CapitalBean"/>
  </bean>
  <bean id="CapitalBean" class="org.arpit.javapostsforlearning.Capital">
      <property name="capitalName" value="Delhi"/>
  </bean>
</beans>
Here We have declared two beans with corresponding ids.
1.Class Country with id as "CountryBean"
2.Class Capital with id as "CapitalBean"
Property's value tag is for assigning value to corresponding attribute. so In above xml file,we have assigned countryName attribute of Country class with value as india
<property name="Name Of Attribute" value="Value Of attribute to be assigned"/>
Property's ref tag is for assigning reference to corresponding attribute. so In above xml file,we have assigned reference of Capital class to capital attribute of Country class.
<property name="Name Of Attribute" ref="id of referencing bean"/>

5.Run it

When you will run above application,you will get following as output.

Delhi is capital of India

Source code:

In next post,we will see dependency injection via constructor

This is 4 of 16 parts of tutorial series

Tutorial Content: Spring tutorial for beginners

    Introduction to spring framework Spring interview questions Dependency injection(ioc) in spring Spring hello world example in eclipse Spring java based configuaration Dependency injection via setter method in spring Dependency injection via constructor in spring Spring Bean scopes with examples Initializing collections in spring Beans Autowiring in spring Inheritance in Spring Spring ApplicationContext Spring lifetime callbacks BeanPostProcessors in Spring Annotation based Configuration in spring Spring AOP tutorial

After having some basic understanding of spring framework now we are ready to create Hello world example.
Firstly download required jars and docs from Spring Downloads | SpringSource.org
Now,In eclipse IDE,click on File->new














Click on other and then select java project


Click on next and  Write project name.I have writtern here "HelloWorldInSpring3"

Click on finish and now our project is created

Create new folder "jars" under src folder so for that right click on project->new->folder


Write folder name as "jars"



click on finish and empy jar folder will be created in src folder.

Now we will add the Spring 3. libraries to the project. Extract the "spring-framework-3.1.1.RELEASE-with-docs.zip" file if you have not extracted. Now go to the "dist" directory of the and then copy all the jar files (Ctrl+C) and paste on the jars directory (of our project) in the Eclipse IDE.

Then find the commons-logging.jar from extracted folder and also copy this file into Eclipse IDE. You will find this library into spring-framework-3.0.0.RELEASE-with-docs\spring-framework-3.1.1.RELEASE\projects\spring-build\lib\ivy folder.

Now add all the jars to "Java Build Path". Right click on the "Spring3HelloWorld" in project explorer and then select properties. Then select "Java Build Path" --> Libraries and then click on the "Add JARs" button. And add all the libraries to Java Build Path.



Create a new package org.arpit.javapostsforlearning to hold the java files. Right click on the "src" folder and then select New --> Package. Then provide the package name as org.arpit.javapostsforlearning and click on the "Finish" button. 


Create a new Java file Spring3HelloWorld.java under the package org.arpit.javapostsforlearning and add the following code:


package org.arpit.javapostsforlearning;

public class Spring3HelloWorld {

    String name;
    
    public void printHello()
    {
        System.out.println("Hello World from "+name);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
}


now create a Xml file called Spring3HelloWorld in src folder.Add following content to it

<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="Spring3HelloWorldBean"
class="org.arpit.javapostsforlearning.Spring3HelloWorld">
<property name="name" value="arpit"/>
 </bean>

</beans>


Here <beans> tag is for defining multiples beans.All beans of our program are defined in <beans> tag
<bean> tag is for defining a single bean.
"id" is for providing unique identification to bean.
"class" is fully qualified name of class
"property" is used for defining attribute of bean class.

The above xml file declares the spring bean "Spring3HelloWorldBean" of the class org.arpit.javapostsforlearningSpring3HelloWorld.

Create another java file named "Spring3HelloWorldMain.java" under package org.arpit.javapostsforlearning.Copy following content in "Spring3HelloWorldMain.java" file

package org.arpit.javapostsforlearning;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class Spring3HelloWorldMain {

       public static void main(String[] args) {

              ApplicationContext beanFactory = new ClassPathXmlApplicationContext("spring3HelloWorld.xml");

              Spring3HelloWorld myBean = (Spring3HelloWorld) beanFactory.getBean("Spring3HelloWorldBean");
              myBean.printHello();
    }

}

In the above code we have created the instance of ApplicationContext and the retrieved the "Spring3HelloWorldBean". Then we called the printHello() method on the bean.

Run program:

right click on project->Run as->Java Application

Output is :

Hello World from arpit

Source code:


In next post ,we will see dependency injection via setter method.

 

Java tutorial for beginners Copyright © 2012