How to inject prototype dependency in a singleton bean


As we know once the singleton bean is created all the properties object defined in it are created once. But what about special and rare case in which one of the property object needs to be created everytime the singleton object is required. for example i have put a property in a singleton object as Timestamp, which can tell me when my singleton object was accessed. For this I need to know the exact time when the object is fetched and not created.
Possible solution could be everytime the method “getInstance()” is called a new Timestamp object is created and injected into spring object.
This is also possible in Spring using look-up method injection.
Lookup method injection refers to the ability of the container to override methods on container managed beans, to return the result of looking up another named bean in the container. The lookup will typically be of a prototype bean.

public abstract class SingletonBean{
public abstract Timestamp getCurrentTime();
}


In spring.xml
< bean id="mySingleton" class="com.SingletonBean" >
< lookup-method name="getCurrentTime" bean="currentTimeBean"/ >
< / bean >
< bean id ="currentTimeBean" class="java.sql.TimeStamp" scope="prototype"/ >

It is mandatory to make currentTimeBean as prototype otherwise same instance of bean will be passed.

Dependency Injection in Spring


Dependency Injection (DI): is a way to let the framework or the container work out the complexities of service instantiation, initialization and sequencing and supplies the service references to the clients as required. In spring IOC container has the responsibility of doing DI.

 

Consider a simple example:

 

public interface Vehicle {

                 void displayData();

}

 

A FourWheeler class implements Vehicle interface.

 

public class FourWheeler implements Vehicle {

 

      private String name;

      private int purchaseValue;

      private int noOfTyres;

      public FourWheeler(){}                          // default constructor                   

public FourWheeler(String name, int purchaseValue, int noOfTyres) {

            super();

            this.name = name;

            this.purchaseValue = purchaseValue;

            this.noOfTyres = noOfTyres;

      }

      public void displayData() {

            System.out.println(” Name of vehicle is “+ name);

            System.out.println(“Purchase Value is “ +purchaseValue);

            System.out.println(“Tyres the vehicle has “ +noOfTyres);

      }

      public String getName() {

            return name;

      }

      public void setName(String name) {

            this.name = name;

      }

      public int getPurchaseValue() {

            return purchaseValue;

      }

      public void setPurchaseValue(int purchaseValue) {

            this.purchaseValue = purchaseValue;

      }

      public int getNoOfTyres() {

            return noOfTyres;

      }

      public void setNoOfTyres(int noOfTyres) {

            this.noOfTyres = noOfTyres;

      }

}

 

The different ways in which the class can be instantiated using DI in spring.xml:

 

1) Setter based injection: The values of the properties of the class are set with the help of setter. Each class needs to declare the setter of the properties and their values are set from the spring configuration file.

 

 <?xml version=“1.0” encoding=“UTF-8”?>

<!DOCTYPE beans PUBLIC “-//SPRING//DTD BEAN//EN” http://www.springframework.org/dtd/spring-beans.dtd&#8221;>

<beans>      

       <bean id=“fourWheeler” class=“com.src.FourWheeler”> 

            <property name=“noOfTyres”> <value>4</value>

            </property>

           

<property name=“name” value=“Honda”/>                                  

<property name=“purchaseValue” value=“900000”/>  

      </bean>

</beans>

 

In above example the setter methods are created for noOfTyres, name, purchaseValue in FourWheeler  class and the values are set using <property> <value> tag in xml file.

Note that for each property the value is set using a different syntax. All syntaxes are valid and

can be used depending on the programmer liking. In this declaration the default constructor of class is called.

 

2)  Constructor Based injection: In this case the values are set using constructor of the java class. The call to constructor is made from the xml file using <constructor-arg>.  For the above mentioned java class constructor injection will be:

 

<?xml version=“1.0” encoding=“UTF-8”?>

<!DOCTYPE beans PUBLIC “-//SPRING//DTD BEAN//EN” http://www.springframework.org/dtd/spring-beans.dtd&#8221;>

<beans >      

     

      <bean id=“fourWheeler” class=“com.src.FourWheeler”> 

                        <constructor-arg> index=“0” value=“Honda”/>

                        <constructor-arg type=“Integer”>

                              <value>900000</value>

                  </constructor-arg>

      </bean>    

</beans>

 

 

In the above example the values to the bean is passed using <constructor-arg>. The sequence in which the parameters are passed should match with the constructor available in the class.

 

3) Static factory method: In the less common case where the container invokes a static, factory method on a class to create the bean, the class property specifies the actual class containing the static factory method that is to be invoked to create the object (the type of the object returned from the invocation of the static factory method may be the same class or another class entirely.

 

Consider the following method present in FourWheeler class:

public static TwoWheeler createInstance(){

            return new TwoWheeler();

      }

 

Note that the method has to be static. And following line of code in xml:

 

<bean id=“twoWheeler” class=“com.src.FourWheeler” factory-method=“createInstance”/>

 

After execution of the above line twoWheleler bean will represent the TwoWheeler object which is created by calling the function from FourWheeler Class. The attribute factory-method tells which method to call present in the class mentioned. This scenario could possibly use in cases where Factory pattern is required.

 

4) Instance Factory method: In this case instead of having a static method a non-static method is present to create the object.

 

Consider the following method present in FourWheeler class:

public TwoWheeler createInstance(){

            return new TwoWheeler();

      }

 

Note that the method need not be static. And following line of code in xml:

 

<bean id=“parentfourWheeler” class=“com.src.FourWheeler”/>

 

<bean id=“fourWheeler” factory-bean = “parentFourWheeler” factory-method=“createInstance” />

 

Here the twoWheeler object is created from a non-static method of class FourWheeler.

Introduction to Spring Part II – Bean, BeanFactory, ApplicationContext, IOC


In this technoticle I will be explaining some of the basic concepts of Spring :

Bean – It is the basic element of the framework. It is equivalent to an object created in java. In spring bean can be created using following methods:

1)      Setter injection

2)      Constructor injection

3)      Interface injection

4)      Static factory method

5)      Instance method

The detailed explanation is Dependency Injection

BeanFactory – As the name suggest the beanfactory instantiate, configure and manages all beans defined. These beans typically collaborate with one another, and thus have dependencies between themselves. The ways by which beanFactory can be created: 

  • InputStream is = new FileInputStream(“beans.xml
    XmlBeanFactory factory = new XmlBeanFactory(is);
  •  

  • ClassPathResource res = new ClassPathResource(“beans.xml”); 
    XmlBeanFactory factory = new XmlBeanFactory(res);
  •  

  • ClassPathXmlApplicationContext appContext =  new ClassPathXmlApplicationContext (new String[] { “applicationContext.xml”,”applicationContext-part2.xml”}
    BeanFactory factory = (BeanFactory) appContext;

When any of the above lines are executed all beans present in the “configuration” file(s) are instantiated and stored in the bean factory.Once the bean factory is loaded the bean can be retrieved:

 

   BeanClassName beanObj = (BeanClassName) factory.getBean(“beanName”);

 

ApplicationContext: ApplicationContext extends BeanFactory and thus provide extra functionality than BeanFactory.

The following are the additional functionalities:

·         MessageSource, providing access to messages in, i18n-style

·         Access to resources, such as URLs and files

·         Event propagation to beans implementing the ApplicationListener interface

·         Loading of multiple (hierarchical) contexts, allowing each to be focused on one particular layer, for example the web layer of an application

Invresion of Control – Earlier the control of interface was with the application program. For example it a typical user input application a prompt will pop up saying ‘Enter Name’ or at some place the property has to be set explicitly using the setter methods. But with the advent of IOC, now it’s the responsibility of the container in which beans are loaded to find the correct value of a property with the help of spring configuration file and now not much responsibility is left to the application program to set or get the values.IOC is too generic term, so spring generally designates it as Dependency Injection (DI). 

 A typical IOC container would look like:

IOC Container
IOC Container

 

  • An IOC can have multiple ApplicationContexts.
  • ApplicationContext can also refer other application context.
  • Applicationcontext can contain another applicationcontext.
  • Multiple beanfactories can be inserted in an applicationcontext.

Introduction to Spring -Part 1


Here is my first technoticle (technical +article) to give an introduction of Spring.

 

Spring released its first version around 5 yrs back and in a short span of time it has gained huge popularity and now it has become one of the main building components of J2EE application. It has progressed from version 1.2 to the present 2.5, and has been adopted in an even wider range of industries and projects.

I believe Spring has gained huge popularity because:

  1. It is managed by a light weight container known as Inverse Of Control (IOC).
  2. It is modular in design. The various functionalities are modeled separately such that each module can work as an independently with the support of other modules.
  3. It has managed to overcome the EJB drawbacks, especially the cumbersome configuration need to be done just to create a bean.
  4. Applications built using Spring are very easy to test. For certain unit testing scenarios, the Spring Framework provides mock objects and testing support classes. Spring also provides unique “integration testing” functionality in the form of the Spring TestContext Framework and legacy JUnit 3.8 support classes that enable you to test your code quickly and easily, even while accessing a staging database.
  5. Spring is essentially a technology dedicated to enabling you to build applications using Plain Old Java Objects.
  6. Spring provides integration and support for many other technologies like Jsp, Struts, EJB, Hibernate etc.
  7. Spring helps in writing less redundant code and also separates the configuration code in a xml file.

 

The basic overview of Spring framework is:

 

 

 

The Core package is the most fundamental part of the framework and provides the IoC and Dependency Injection features. The main functionality of the container is to create and mangae beans. The Context package build on the solid base provided by the Core package: it provides a way to access objects in a framework-style manner in a fashion somewhat reminiscent of a JNDI-registry. The context package inherits its features from the beans package and adds support for internationalization (I18N) (using for example resource bundles), event-propagation, resource-loading, and the transparent creation of contexts by, for example, a servlet container.

The DAO package provides a JDBC-abstraction layer that removes the need to do tedious JDBC coding and parsing of database-vendor specific error codes. Also, the JDBC package provides a way to do programmatic as well as declarative transaction management, not only for classes implementing special interfaces, but for all your POJOs (plain old Java objects).

The ORM package provides integration layers for popular object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis. Using the ORM package one can use all those O/R-mappers in combination with all the other features Spring offers, such as the simple declarative transaction management feature mentioned previously.

Spring’s AOP package provides an AOP Alliance-compliant aspect-oriented programming implementation allowing you to define, for example, method-interceptors and pointcuts to cleanly decouple code implementing functionality that should logically speaking be separated.

Spring’s Web package provides basic web-oriented integration features, such as multipart file-upload functionality, the initialization of the IoC container using servlet listeners and a web-oriented application context. When using Spring together with WebWork or Struts, this is the package to integrate with.

 

Spring’s MVC package provides a Model-View-Controller (MVC) implementation for web-applications. Spring’s MVC framework is not just any old implementation; it provides a clean separation between domain model code and web forms, and allows you to use all the other features of the Spring Framework.

 

The main features which Spring has come up with:

1)      Inversion Of Control (IOC)

2)      Dependency Injection (DI)

3)      Aspect Oriented Programming (AOP)

4)      JDBC

5)      RMI

6)      MVC layer for J2EE Application

7)      Web flow

 

 

Each feature above me will be explaining one by one.

 In the next article I will explain IOC.