Ad

Thursday, 19 March 2015

Implementing logging using spring AOP

In this post we will see how to implement the logging using spring AOP. Logging is one of the cross cutting concerns which span across the multiple layer in the application.Using Spring AOP  we don't need to write the logging statements in each and every method of the class which needs to be logged.Instead we will define the cross cutting concern which is logging in our case in a single aspect(i.e Class) and we will make this aspect to execute in and around of the matched joint point(i.e method execution in spring AOP).

Below code example will give us an better idea on this.

Employee - Class for which we like to enable the logging.
LoggingAspect - Aspect class which contains and execute the advice on the employee bean.
aop.xml - Metadata information to the spring container.
AspectTest - Class which loads the spring container and gets the employee bean from the container                         and invokes the method on it.

Employee.java

package aspect;

public class Employee {

private String id=null;

private String name=null;

private double salary=0;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

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

public double getSalary() {
return salary;
}

public void setSalary(double salary) {
this.salary = salary;
}

public Double getAnnualSalary()
{
return new Double(salary*12);
}
 
public Double decrementSalary()
{
String decValue=null;
return new Double(decValue);
}
}

LoggerAspect.java

package aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class LoggerAspect {

@Pointcut("execution(* aspect.*.*(..))")
public void selectall(){}

@Around("selectall()")
public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable
{
String className=joinPoint.getTarget().getClass().getName();
String methodName=joinPoint.getSignature().getName();
System.out.println("Start of the Method "+className+":"+methodName);
Object object=joinPoint.proceed();
System.out.println("End of the Method "+className+":"+methodName);
return object;
}

@AfterReturning(pointcut="selectall()",returning="retvalue")
public void AfterReturningAdvice(JoinPoint joinPoint,Object retvalue)
{
String className=joinPoint.getTarget().getClass().getName();
String methodName=joinPoint.getSignature().getName();
if(retvalue!=null)
System.out.println("Value returned from method "+className+":"+methodName+"
                is:"+retvalue);
}

@AfterThrowing(pointcut="selectall()",throwing="ex")
public void AfterThrowingAdvice(JoinPoint joinPoint,Exception ex)
{
String className=joinPoint.getTarget().getClass().getName();
String methodName=joinPoint.getSignature().getName();
System.out.println("Exception encountered in Method "+className+":"+methodName
+" and exception is:"+ex.toString());
}
}


Pointcut and JointPoints

@Pointcut - Pointcut will define the joint point i.e method execution for which the logging has to be enabled.This pattern(execution(* aspect.*.*(..))) will match any method execution  in the class of  aspect package which  contains zero or more arguments.

Types of advice- Aspect will execute the below advice on the target object i.e on employee bean.

@Around - This advice will be executed both before and after the method execution(which matches with the defined pointcut).
@AfterReturningAdvice - This advice will be executed after the method execution(which matches with the defined pointcut) is returned normally without any exception.
@AfterThrowing - This advice will be executed when the exception is returned from the method execution(which matches with the defined pointcut).

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

<aop:aspectj-autoproxy/>

<bean id ="employee" class="aspect.Employee">
<property name="id" value="E12"/>
<property name="name" value="Rahul"/>
<property name="salary" value="3120"/>
</bean>

<bean id="aspectannot" class="aspect.Aspect"/>

</beans>


AspectTest.java


package aspect;

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

public class AspectTest {

  public static void main(String[] args) {

  ApplicationContext context= new ClassPathXmlApplicationContext(new String[]{"aop.xml"});
  Employee emp= context.getBean("employee", Employee.class);
  double annualSalary=emp.getAnnualSalary();//1
  try
  {
  double decSalary=emp.decrementSalary(0);//2
  }
  catch(Exception e)
  {
 //ignore the exception
  }
  }

}


OUTPUT

Start of the Method aspect.Employee:getAnnualSalary
End of the Method aspect.Employee:getAnnualSalary
Value returned from method aspect.Employee:getAnnualSalary is:37440.0
Start of the Method aspect.Employee:decrementSalary
Exception encountered in Method aspect.Employee:decrementSalary and exception is:java.lang.NullPointerException

As we can see in the output,on each method execution of the employee bean corresponding advises was executed by the LoggerAspect.

Monday, 9 March 2015

BeanCurrentlyInCreationException: Error creating bean with name : Requested bean is currently in creation: Is there an unresolvable circular reference?

In this post we will see how to resolve this exception-"BeanCurrentlyInCreationException: Error creating bean with name : Requested bean is currently in creation: Is there an unresolvable circular reference?" in spring.This exception is thrown in the below scenario:
  1. When there is an circular reference between the beans. For instance ClassA contains the instance member of type ClassB and class B too has ClassA as instance member. 
  2. And we use the constructor arguments to inject the dependencies between these beans.
Below code sample will explain this scenario.
  • ClassA,ClassB- bean classes for which there is an  circular dependencies between them.
  • CircularDemo -Main class which will load and initialize the spring container.
  • circontext.xml - metadata configuration details for the spring container.
ClassA.java

package test;

public class ClassA {

private ClassB classB=null;

public ClassB getClassB() {
return classB;
}

public void setClassB(ClassB classB) {
this.classB = classB;
}

@Override
public String toString() {
return "ClassA";
}

}

ClassB.java

package test;

public class ClassB {

private ClassA classA=null;

public ClassA getClassA() {
return classA;
}

public void setClassA(ClassA classA) {
this.classA = classA;
}

@Override
public String toString() {
return "ClassB";
}
}

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

<bean id="classA" class="test.ClassA">
<constructor-arg ref="classB"/>
</bean>

<bean id="classB" class="test.ClassB">
<constructor-arg ref="classA"/>
</bean>

</beans>

As we can see in the application context file,we used the constructor arguments to inject the dependencies for bean ClassA and ClassB

CircularDemo.java

package test;

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

public class CircularDemo {

public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext bf= new ClassPathXmlApplicationContext(new String[]
               {"circontext.xml"});
ClassA classA= bf.getBean("classA",ClassA.class);
   System.out.println("Bean Loaded:"+classA);
}
}

OUTPUT:

When we run the main program - CircularDemo,we will get the below exception

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'classA' defined in class path resource [circontext.xml]: Cannot resolve reference to bean 'classB' while setting constructor argument; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'classB' defined in class path resource [circontext.xml]: Cannot resolve reference to bean 'classA' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'classA': Requested bean is currently in creation: Is there an unresolvable circular reference?

To resolve this exception,declare the dependencies between the beans through the property setters instead of the constructor arguments as shown below.

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

<bean id="classA" class="test.ClassA">
<property name="classB" ref="classB"/>
</bean>

<bean id="classB" class="test.ClassB">
<property name="classA" ref="classA"/>
</bean>

</beans>

Now if we run the CircularDemo with the above application context file,we will get the expected output.

Bean Loaded:ClassA

Saturday, 7 March 2015

No matching bean of type [] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency

In this post we will see how to resolve this exception-"NoSuchBeanDefinitionException:No matching bean of type [] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency" in spring.Click this  link to know about the autowire feature in spring and the various types.Coming back to our topic, this exception is thrown in the below scenario:
  1. When we  autowire the bean collaborators by constructor type,so that the spring container will resolve the bean dependencies automatically
  2. And there was  no bean declared or exist in the application context which is same as type of the constructor argument of the bean to be autowired.
Below code sample will explain this scenario.
  • Car- bean class for which the dependencies has to be resolved automatically by their constructor arguments type.
  • Engine - bean class which is set as the property of the Car object .
  • CarDemo -main class which will load the spring container and get the car bean from the container.
  • carcontext.xml - metadata configuration details for the spring container.
Car.java

package test;

public class Car {

private Engine engine=null;

public Car(Engine engine) {
super();
this.engine = engine;
}

public Engine getEngine() {
return engine;
}

@Override
public String toString() {
return "Car [engine=" + engine + "]";
}
}

Engine.java

package test;

public class Engine {

private int engineNumber;

private int engineCost;

public int getEngineNumber() {
return engineNumber;
}

public void setEngineNumber(int engineNumber) {
this.engineNumber = engineNumber;
}

public int getEngineCost() {
return engineCost;
}

public void setEngineCost(int engineCost) {
this.engineCost = engineCost;
}

@Override
public String toString() {
return "Engine [engineNumber=" + engineNumber + ", engineCost="
+ engineCost + "]";
}
}

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

<bean id="car" class="test.Car" autowire="constructor">
</bean>

</beans>

As we can see in the application context file,we used the attribute autowire="constructor" to make the container to automatically inject and resolve the dependencies for the car bean.Since the Car bean has the constructor of argument type test.Engine,container will look for the bean of type "test.Engine" and inject the same.

CarDemo.java

package test;

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

public class CarDemo {

public static void main(String[] args) {
ApplicationContext bf= new ClassPathXmlApplicationContext(new String[]{"carcontext.xml"});
Car car= bf.getBean("car",Car.class);
   System.out.println(car);
}

}


OUTPUT:

When we run the main program - CarDemo,we will get the below exception

Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'car' defined in class path resource [carcontext.xml]: Unsatisfied dependency expressed through constructor argument with index 0 of type [test.Engine]: : No matching bean of type [test.Engine] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [test.Engine] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray
(ConstructorResolver.java:730)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor
(ConstructorResolver.java:196)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory
.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1003)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance
(AbstractAutowireCapableBeanFactory.java:907)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean
(AbstractAutowireCapableBeanFactory.java:485)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean
(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject
(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton
(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean
(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean
(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons
(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization
(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh
(AbstractApplicationContext.java:464)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
at test.CarDemo.main(CarDemo.java:9)

While autowiring the dependencies for the car bean by constructor arguments, container could not found a bean of type test.Engine and hence this exception was thrown.

To resolve this,make sure we declare a bean of type test.Engine in the application context file so that the container will inject the same to Car bean by autowiring.

<bean id="engine" class="test.Engine">
<property name="engineNumber" value="2301"/>
<property name="engineCost" value="120000"/>
</bean>

Now if we run the CarDemo with the above change in the carcontext.xml,we will get the expected output

Car [engine=Engine [engineNumber=2301, engineCost=120000]]

Thursday, 5 March 2015

No unique bean of type [] is defined: expected single matching bean but found 2

In this post we will see how to resolve the exception-"NoSuchBeanDefinitionException:No unique bean of type [] is defined: expected single matching bean but found 2" in spring.By using autowiring feature in spring,we can make the spring container to resolve the bean dependencies automatically and hence we don't need to declare the dependencies either through constructor arguments or through properties in the application context file.We can autowire the beans by:
  • ByName  - spring container will autowire the dependencies by looking up the bean name in the application context file which will match with the bean property name.Lets says  a bean X has the property y(has the setY method too) and the  spring container will look for the bean named "y" in the application context and inject the same to bean X.
  • ByType   - spring container will autowire the property with the bean which has the same type.If more than one bean exists in the container of the same type,then the above fatal exception is thrown
  • Constructor - Its as same as ByType,but it applies to the argument type of the bean to be autowired.If more than one bean or no bean exist in the container of the same constructor type then the above fatal exception is thrown.
Let say we have the below classes and we would like to autowire the  dependencies by type.
  • Bus - Bean class for which the container has to autowire the dependencies by type.
  • Engine - Bean class which is set as the property of the bus object.
  • BusDemo -Main class which will load the spring container and get the bus bean from the container.
  • buscontext.xml - metadata configuration details for the spring container.
Bus.java

package test;

public class Bus {
private Engine engine=null;

public Engine getEngine() {
return engine;
}

public void setEngine(Engine engine) {
this.engine = engine;
}

        @Override
public String toString() {
return "Bus [engine=" + engine + "]";
}
}
   

Engine.java

package test;

public class Engine {
private String engineMake;
private String engineCost;

public String getEngineMake() {
return engineMake;
}

public void setEngineMake(String engineMake) {
this.engineMake = engineMake;
}

public String getEngineCost() {
return engineCost;
}

public void setEngineCost(String engineCost) {
this.engineCost = engineCost;
}
       
        @Override
public String toString() {
return "Engine [engineMake=" + engineMake + ", engineCost="
+ engineCost + "]";
} 
}

buscontext.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.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="bus" class="test.Bus" autowire="byType">
</bean>

<bean id="primaryengine" class="test.Engine">
<property  name="engineMake" value="Ford"/>
<property  name="engineCost" value="100000"/>
</bean>

<bean id="secondaryengine" class="test.Engine">
<property  name="engineMake" value="Renault"/>
<property  name="engineCost" value="50000"/>
</bean>

</beans>

As we can see in the application context file,we use the attribute autowire="byType" to make the container to automatically inject and resolve the dependencies for the bus bean.Container will look for the bean of type "test.Engine" and inject the same to the engine property of the bus bean.

BusDemo.java

package test;

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

public class BusDemo {
public static void main(String[] args) {
ApplicationContext bf= new ClassPathXmlApplicationContext(new String[]  
               {"buscontext.xml"});
Bus bus= bf.getBean("bus",Bus.class);
       System.out.println(bus);
}

}

OUTPUT:

When we run the main program - BusDemo,we will get the below exception

Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bus' defined in class path resource [buscontext.xml]: Unsatisfied dependency expressed through bean property 'engine': : No unique bean of type [test.Engine] is defined: expected single matching bean but found 2: [primaryengine, secondaryengine]; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [test.Engine] is defined: expected single matching bean but found 2: [primaryengine, secondaryengine]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType
(AbstractAutowireCapableBeanFactory.java:1167)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean
(AbstractAutowireCapableBeanFactory.java:1059)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean
(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean
(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject
(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton
(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean
(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean
(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons
(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization
(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh
(AbstractApplicationContext.java:464)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
at test.BusDemo.main(BusDemo.java:9)

While autowiring the dependencies for the bus bean, container found two beans of type  test.Engine instead of one and hence this exception was thrown

We can resolve this exception either in two ways.Let say we want the container to autowire the dependency for the bus bean with the primaryengine bean.

1)Set the primary attribute of the primaryengine bean to true,so that the container will nominate this bean to inject it to the bus bean by autowiring

   <bean id="primaryengine" class="test.Engine" primary="true">
   <property  name="engineMake" value="Ford"/>
   <property  name="engineCost" value="100000"/>
   </bean>

or

2)Set the autowire-candidate attribute of the secondaryengine bean to false,so that the container will exclude this bean for autowiring  and hence inject the primaryengine bean to the bus bean. 

<bean id="secondaryengine" class="test.Engine" autowire-candidate="false">
<property  name="engineMake" value="Renault"/>
<property  name="engineCost" value="50000"/>
</bean>

Now if we run the BusDemo with the change(either option 1 or 2 as above) in the buscontext.xml,we get the below output

Bus [engine=Engine [engineMake=Ford, engineCost=100000]]

Wednesday, 4 March 2015

@ConstructorProperties annotation in spring IOC

@ConstructorProperties is used in constructor based dependency injection.It is mainly used when we need the constructor arguments passed in the application context(metadata to the spring container) should be resolved by the constructor parameter name in the bean object to be created.By annotating @ConstructorProperties in the constructor of the bean class,it will make the constructor parameter names available to the spring container at runtime.Below sample will show how this annotation can be used:
  • Person - Bean class in which container will inject the dependencies through constructor arguments
  • personcontext.xml - metadata configuration details for the spring container
  • PersonDemo - Main class which will load the spring container and get the person bean from the container.

Person.java

package test;

import java.beans.ConstructorProperties;

public class Person {
private String name;

private int age;

@ConstructorProperties({"pername", "perage"})
public Person(String pername, int perage) {
super();
this.name = pername;
this.age = perage;
}

public String getName() {
return name;
}

public int getAge() {
return age;
}

@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}

Since we have annotated the  constructor parameters with @ConstructorProperties,the constructor parameter names(pername and perage) will be available to Spring container at runtime.

personcontext.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.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="person" class="test.Person">
<constructor-arg  name="pername" value="Ram"/>
<constructor-arg  name="perage" value="21"/>
</bean>
</beans>

As we can see in the application context file,we use the constructor parameter names to inject the dependencies.

PersonDemo.java

package test;

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

public class PersonDemo {
public static void main(String[] args) {

   ApplicationContext bf= new ClassPathXmlApplicationContext(new String[]         
           {"personcontext.xml"});
   Person person= bf.getBean("person",Person.class);
   System.out.println(person);
}
}


OUTPUT

Person [name=Ram, age=21]

Tuesday, 3 March 2015

Bean creation in spring using factory method

Sometimes we will not need the spring container to instantiate the bean class.Instead we might need to use the Factory method(pattern) to instantiate the bean object.Lets says we have the below hierarchy of Classes
  • IProduct - Interface for  all the Product Classes
  • ProductOne,ProductTwo- Product concrete Implementation classes which implements the IProduct Interface
  • ProductFactory - Factory Class which creates the Object of type IProduct
IProduct.java

package test;

public interface IProduct {
public abstract void  doOperation();
}

ProductOne.java

package test;

public class ProductOne implements IProduct{

public ProductOne(String name) {
super();
this.name = name;
}

String name;

public String getName() {
return name;
}

@Override
public void doOperation() {
System.out.println("Done for Product:"+name);
}
}

ProductTwo.java

package test;

public class ProductTwo implements IProduct{
public ProductTwo(String name) {
super();
this.name = name;
}

String name;

public String getName() {
return name;
}

@Override
public void doOperation() {
System.out.println("Done for Product:"+name);
}
}


ProductFactory.java

package test;

public class ProductFactory {
public static IProduct getProduct(int productId)
{
IProduct product=null;
if(productId==1)
{
product=new ProductOne("ProductOne");
}
else if(productId==2)
{
product=new ProductTwo("ProductTwo");
}
return product;
}

}

we should use the class attribute to specify the name of the factory class and the factory-method attribute to specify the static factory method which will instantiate the bean.We can pass the value to this factory method by using the constructor-arg tag as shown below.

productcontext.xml

<?xml version="1.0" encoding="UTF-8"?&gt;
<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.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="productbean1" class="test.ProductFactory" factory-method="getProduct">
<constructor-arg  value="1"/>
</bean>
<bean id="productbean2" class="test.ProductFactory" factory-method="getProduct">
<constructor-arg  value="2"/>
</bean>
</beans>


ProductDemo.java

package test;

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

public class ProductDemo {

public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext bf= new ClassPathXmlApplicationContext(new String[]            
               {"productcontext.xml"});
   IProduct product1= bf.getBean("productbean1",IProduct.class);
   product1.doOperation();
   IProduct product2=bf.getBean("productbean2",IProduct.class);
   product2.doOperation();
}
}

When we ask for the bean productbean1 and productbean2,the spring container will delegate the call to the factory class "ProductFactory" to instantiate the bean object

OUTPUT

Done for Product:ProductOne
Done for Product:ProductTwo

Sunday, 8 February 2015

To implement Binary Search algorithm in Java

Below program sample will show how to search for a particular element in the array using binary search.Make sure the array is sorted before we use the binary search.Binary search algorithm is very fast when compared to linear search(where each element in the array is checked).
Binary Search algorithm is pretty simple:
  • First it will check the middle element of the array.
  • If it is smaller than the search element,then the first part of the array is considered for the further search(leaving behind the second part),
  • Else the second part of the array is considered for the further search.
  • The above logic is continued until we find the search element or the start index of the filtered array is not greater than end index(where the element is not found)
public class BinarySearchSample {                                                                                                      

public static void main(String[] args) {

int [] arry= new int[]{3,5,9,13,25,40,55,90,121,150};
        int low=0;
        if(args.length==0)
        {
        System.out.println("Please pass the element to search in the array");
        }
        int src=Integer.parseInt(args[0]);//element to Search for
        int mid=0;
        int high=arry.length-1;
        boolean isFound=false;
        while(low<=high)
        {
        mid=(low+high)/2;
        System.out.println("low:"+low+" mid:"+mid+" high:"+high);
        if(src<arry[mid])
        {
        high=mid-1;
        }
        else if(src > arry[mid])
        {
        low=mid+1;
        }
        else
        {
        isFound=true;
        break;
        }        
        }
if(isFound)
{
System.out.println("Found "+src+" at index:"+mid);
}
else
{
System.out.println(src+" not found");
}
}
}

Output:

When you run the above program by passing the argument as 150(element to search for),we will get the below output

low:0 mid:4 high:9                                                                                                                                  
low:5 mid:7 high:9
low:8 mid:8 high:9
low:9 mid:9 high:9
Found 150 at index:9

If we analyse the above output,binary search took only 4 iterations to find the last element in the array,whereas in linear search it will take 10 iterations to find the same element in the above array.