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.

how to access properties file in Spring


PropertyPlaceHolderConfigurer A property resource configurer that resolves placeholders in bean property values of context definitions. It pulls values from a properties file into bean definitions.

The default placeholder syntax follows the Ant / Log4J / JSP EL style: ‘$’

PropertyOverrideConfigurer A property resource configurer that overrides bean property values in an application context definition. It pushes values from a properties file into bean definitions
Example:
A simple class of which values are set from property file.

public class MyBean {

private String myName;
private String password;
/**
* @param args
*/
public static void main(String[] args) {

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("mybean.xml");
MyBean bean = (MyBean)ctx.getBean("myBean");
// getting the properties from the property file
System.out.println(bean.getMyName());
System.out.println(bean.getPassword());
}
public String getMyName() {
return myName;
}
public void setMyName(String myName) {
this.myName = myName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}

}

The xml file config

<?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-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
default-lazy-init="true">

<bean id="configProperties"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>config.properties</value>
</list>
</property>
</bean>

<bean id="myBean" class="test.tetst.MyBean">
<property name="myName" value="${myname}" />
<property name="password" value="${password}" />
</bean>
</beans>

config.properties files
myname=testing
password=password

Can an Innerclass be instantiated in Spring?


Dont be surprise but the answer is yes..

package com.src;
public class MyClass{
public static class InnerClass{
}
}

In spring.xml it Innerclass can be instantiated as:

< bean id="myclass" class="com.src.MyClass$InnerClass">

Wow !! this is good , spring is amazing.The innerclass should be public and static only.
But i am wondering ,will  there be any real significance left of InnerClass or not?

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.