Tuesday, December 29, 2009

Simple Spring Application

Spring could be (read intended to be) the one-stop-shop for enterprise application development but at the same time it is light-weight, non-intrusive and modular. Spring allows you to use a particular part/module of spring without bothering about the rest of the spring.


Different types of IoC (Inversion of Control):
Central to the Spring Framework is its Inversion of Control container, which provides a consistent means of configuring and managing Java objects using callbacks. The container is responsible for managing object life cycles: creating objects, calling initialization methods, and configuring objects by wiring them together.
  1. Setter Injection: The examples below are based on setter injection. IoC sets the value of the type parameters of setter methods with the help of bean configuration XML file.
  2. Interface Injection: Spring directly does not support interface injection but there is one thing called autowire, that can be used in spring to achieve some sort of interface injection.
  3. Constructor Injection: constructor injection is almost same like setter injection except only difference that here IoC container initializes the constructor parameters.

Download latest spring framework from http://www.springframework.org

Let's start with sample application using Setter Injection:


First write simple java file call Main.java. It has one subclass call Inject.java which contains some getter and setter methods to set properties. Main class contains main method which loads XML file and set the properties for the Inject class. This code uses spring to load properties from XML file.

The advantage is no need to recompile code again to set different properties. Every time it loads data from XML file. So any change needed just change XML file content.


Code Snapshot:

1. Main.java 

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

public class Main {

public static void main(String[] args) {
XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(
"context.xml"));
Inject demo = (Inject) beanFactory.getBean("mybean");
System.out.println(demo);
}
}

class Inject {

private String name;
private int age;
private String company;
private String email;
private String address;

public void setAddress(String address) {
this.address = address;
}

public void setCompany(String company) {
this.company = company;
}

public void setEmail(String email) {
this.email = email;
}

public void setAge(int age) {
this.age = age;
}

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

@Override
public String toString() {
return String.format("Name: %s\n" +
"Age: %d\n" +
"Address: %s\n" +
"Company: %s\n" +
"E-mail: %s",
this.name, this.age, this.address, this.company, this.email);
}
}

2. context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="mybean"
class="Inject"
p:name="Naman"
p:age="30"
p:address="Bangalore"
p:company="Personal"
p:email="naman.mehta@gmail.com"/>
</beans>


Code compilation needs three jar files in your classpath.
  1. Spring framework jar file
  2. commons-logging.jar
  3. xercesImpl-2.9.1.jar

I recommend, download latest eclipse IDE from http://www.eclipse.org for Java EE developers. Keep jar files in your path or download plug-ins for spring framework.



Will post other samples in next blog... Let me know your comments for the same...

Thursday, December 24, 2009

How to use Factory Method?

Overview:

The factory method pattern is an object-oriented design pattern. Like other creational patterns, it deals with the problem of creating objects (products) without specifying the exact class of object that will be created. The factory method design pattern handles this problem by defining a separate method for creating the objects, whose subclasses can then override to specify the derived type of product that will be created. More generally, the term factory method is often used to refer to any method whose main purpose is creation of objects.


How to create objects runtime?
  1. Write one Interface which has one method called myMethod().
  2. Write some set of Classes which implements this interface.
  3. Write one Class which has one static method which would return different objects based on the argument pass to that method.
Code Snap-shot:
  1. Interface code.

    1.1 myinterface.java
    public interface myinterface {
    public void myMethod();
    }
  2. Some set of Classes.

    2.1 a.java
    public class a implements myinterface {
    public a() {
    System.out.println("I am a...");
    }

    public void myMethod() {
    System.out.println("I am myMethod from a...");
    }
    }
    2.2 b.java
    public class b implements myinterface {
    public b() {
    System.out.println("I am b...");
    }

    public void myMethod() {
    System.out.println("I am myMethod from b...");
    }
    }
    2.3 b1.java
    public class b1 extends b {
    public b1() {
    System.out.println("I am b1...");
    }

    public void myMethod() {
    System.out.println("I am myMethod from b1...");
    }
    }
    2.4 b2.java
    public class b2 extends b {
    public b2() {
    System.out.println("I am b2...");
    }

    public void myMethod() {
    System.out.println("I am myMethod from b2...");
    }
    }

  3. Class which would return object based on the argument pass.

    3.1 test.java
    public class test {
    public test() {
    System.out.println("I am test class...");
    }

    public static myinterface getMyInterface(String ftpType) {
    try {
    if (ftpType.equals("doc")) {
    return (myinterface)Class.forName("a").newInstance();
    } else if (ftpType.equals("html")) {
    return (myinterface)Class.forName("b").newInstance();
    } else if (ftpType.equals("txt")) {
    return (myinterface)Class.forName("b1").newInstance();
    } else if (ftpType.equals("xml")) {
    return (myinterface)Class.forName("b2").newInstance();
    } else {
    return null;
    }
    } catch (Exception e) {
    System.out.println(e);
    return null;
    }
    }

    public static void main (String a[]) {
    myinterface m = test.getMyInterface("txt");
    m.myMethod();
    }
    }

Try this and happy blogging & reading. Any comment pls....