Sunday, July 26, 2009

Simple usage of Spring

Let us look into the concept of Dependency Injection through a small example:-

Here we are trying to print out a string "Hello World" using Spring's techniques. The interface HelloService defines the contract for the service class:-

package com.hello;
public interface HelloService {
void sayHello();
}

HelloServiceImpl implements the above interface as follows:

package com.hello;
public class HelloServiceImpl implements HelloService {
private String hello;
public HelloServiceImpl() {}
public HelloServiceImpl(String hello) {
this.hello = hello;
}
public void sayHello() {
System.out.println(hello);
}
public void setHello(String hello) {
this.hello = hello;
}
}

The property "hello" in this class can be set either through the constructor or the setter method. Now, let us write the Spring Configuration file, named here as hello.xml







Here, the bean named "helloService" of class "HelloServiceImpl" has a property "hello", which is injected with a value of "Hello World" using the setter injection. In effect, this does the following:-

HelloServiceImpl helloService = new HelloServiceImpl();
helloService.setHello("Hello World");

If we were opting for constructor injection, then the tag in the xml file would have to be replaced with -




In effect, this does the following:-

HelloServiceImpl helloService = new HelloServiceImpl("Hello World");


Now, let us write a main class for this entire application, HelloMain.java -

package com.hello;
//add imports and handle exceptions as and when necessary
public class HelloMain {
public static void main (String[] args) {
BeanFactory factory = new XmlBeanFactory(
new FileSystemResource("hello.xml"));

HelloService helloService = (HelloService) factory.getBean("helloService");

helloService.sayHello();
}
}

Here, the BeanFactory is the Spring container. The configuration file "hello.xml" is loaded, "getBean()" retrieves a reference to the bean with id "helloService" and this reference is used to print "Hello World" to the screen.

This example depicts Dependency Injection or Inversion of Control in Spring clearly. Typically, in almost all applications, each object would be responsible for obtaining its own references to the objects it collaborates with, which leads to highly-coupled and hard-to-test code. But here, objects are given their dependencies at creation time by the xml file (in the above example) or dependencies are injected into objects, hence enabling loose-coupling. Here, the interface helps the class to remain loose-coupled at all times.




reference :- Spring in Action

Friday, July 24, 2009

Spring - What is it?

Java was in the process of maturing during the year of 1996. Many rich and dynamic web applications were being developed. But, people started to realize the shortcomings of Java Applets. This paved the way for the invention of Java Beans - a software component model for Java. They were primarily used for building user interface widgets and seemed too simple to be able to do any "real" work. Later in the year if 1998, Enterprise Java Beans (EJB) extended the normal beans to the server side, even though losing its simplicity. Its complexity reduced its popularity and easiness. This is where Aspect Oriented Programming (AOP) and Dependency Injection (DI) found spot to flourish. These methodologies furnish the POJOs (Plain Old Java Object) with a mirror image of an EJB using a declarative programming model, but completly avoiding all the complexities. Better late than never !!!

Leading the development based on lightweight POJOs is the Spring Framework.

Spring is an open source framework, created by Rod Johnson benefitting from its features such as simplicity, testability and loose coupling. Basically, it is a lightweight dependency injection and aspect-oriented container and framework. Breaking it down into simpler terms:-

  • Lightweight -> in size (distributable JAR less than 2.5MB) and overhead of processing
  • Dependency Injection -> loose coupling by means of objects not creating or looking up for dependent objects on their own, instead giving their dependencies during instantiation without being asked by them
  • Aspect-oriented -> separating business logic from system services (logging, security, transaction management) where objects deal with only things they are supposed to do
  • Container -> contains and controls the lifecycle and configuration of application objects
  • Framework -> configures and composes complex applications from simpler components with the help from an XML configuration file
Let us have a peep into the Spring Modules:-
  • Core -> provides the fundamental functionality of Spring, onbased on the BeanFactory
  • ApplicationContext -> builds on top of core and makes Spring a framework, adding support for internationalization messages, application life-cycle events, email, JNDI access, remoting, scheduling, validation, etc.
  • AOP -> decoupling application-wide concerns from objects to which they are applied
  • JDBC abstraction (DAO) -> abstracts away the boilerplate code of JDBC keeping the database code clean and simple, also building meaningful exceptions over the normal SQL Exceptions
  • ORM -> supports various ORM frameworks like Hibernate, JPA, JDO, iBatis, etc in addition to JDBC
  • JMX -> helps expose application's beans as Java Management Extensions beans supporting monitoring and reconfiguring a running application
  • JCA (Java EE Connector API) -> integrates Java applications with various information systems like databases and mainframes, all scattered in disparate servers and platforms
  • MVC Framework -> separates user interface from application logic, also supporting existing MVCs in market like Struts, JSF, etc
  • Portlet MVC -> aggregating several bits of functionality on a single web page providing a view into several applications at once
  • Web -> support classes for MVC applications
  • Remoting -> access applications over the network, expose objects' functionality as remote objects, all considering the objects as simple POJOs
  • JMS -> guarantees message delivery throught JMS message queues and topics and helps create message-driven POJOs capable of consuming asynchronous messages

Thursday, July 9, 2009

EasyMock IllegalStateException: missing behavior definition for last method call

When you encounter this error, please check whether you tried to use the mock object before invoking EasyMock.replay() method. I did that encountered the IllegalStateException and spent quite some time until I figured out the reason.

I had written the following expect() ;

EasyMock.expect(testObj.getTestMethod()).andReturn("testValue");

the culprit was the following statement which I had put before the expect().

System.out.println("testObj="+testObj.getTestMethod());

Hope it helps someone!

JUnit with EasyMock

Ever wondered how could you test your classes without waiting for your colleague to complete his classes.. I think EasyMock is one of the answers..

EasyMock helps to create mock objects by passing an interface as argument. It is very helpful when you have complex web application that involves lot of custom objects and you want to test a particular class which is dependent on ten other classes.

It has 2 simple steps to follow.

1. Create mock objects
2. Set the expected values in mock object so that the methods of the object return the same values

It is very easy to use. (Steps below:-)

1. Add easymock libraries
2. Create JUnit test case
3. Create mock objects using EasyMock.createStrictMock(MyInterface.class)
4. Set expected values using EasyMock.expect(myObj.myMethod()).andReturn("ReturnvaluefromMyMethod").
This statement means that when myMethod() is invoked, return the value "ReturnvaluefromMyMethod". In essence, whichever method you are planning to invoke later, set the values expected to be returned from the method.
5. call EasyMock.replay(myObj);

Our mock objects are ready to use.

Tips:-
1. Do not call any methods of the mock object until you call replay(). Otherwise it will throw an IllegalStateException at that point.

2. If your interface contains getter/setter methods, instruct the getter() [not the setter()] with the expected return values. In general, we are used to invoke the setter method with the value to be set and use the getter methods to retrieve the value.


Hope it helps!