Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Thursday, April 3, 2008

Learn Spring basics through Helloworld Program

Spring jump start

Spring-enabled applications are like any Java application. They are made up of several classes, each performing a specific purpose within the application. What makes Spring-enabled applications different, however, is how these classes are configured and introduced to each other. Typically, a Spring application has an XML file that describes how to configure the classes, known as the Spring configuration file.

The first class that our Springified Hello World example needs is a service class whose purpose is to print the infamous greeting. Listing 1.1 shows GreetingService.java, an interface that defines the contract for our service class.

Listing 1.1 The GreetingService interface separates the service's implementation from its interface.

package com.springinaction.chapter01.hello;
 
public interface GreetingService {
   public void sayGreeting();
}

GreetingServiceImpl.java (listing 1.2) implements the GreetingService interface. Although it's not necessary to hide the implementation behind an interface, it's highly recommended as a way to separate the implementation from its contract.

Listing 1.2 GreetingServiceImpl.java: Responsible for printing the greeting

package com.springinaction.chapter01.hello;
 
public class GreetingServiceImpl implements GreetingService {
   private String greeting;
 
   public GreetingServiceImpl() {}
 
   public GreetingServiceImpl(String greeting) {
      this.greeting = greeting;
   }
 
   public void sayGreeting() {
      System.out.println(greeting);
   }
 
   public void setGreeting(String greeting) {
      this.greeting = greeting;
   }
}

The GreetingServiceImpl class has a single property: the greeting property. This property is simply a String that holds the text that is the message that will be printed when the sayGreeting() method is called. You may have noticed that the greeting can be set in two different ways: by the constructor or by the property's setter method.

What's not apparent just yet is who will make the call to either the constructor or the setGreeting() method to set the property. As it turns out, we're going to let the Spring container set the greeting property. The Spring configuration file (hello.xml) in listing 1.3 tells the container how to configure the greeting service.

Listing 1.3 Configuring Hello World in Spring

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
   "http://www.springframework.org/dtd/spring-beans.dtd">
 
<beans>
   <bean id="greetingService"
         class="com.springinaction.chapter01.hello.GreetingServiceImpl">
      <property name="greeting">
         <value>Buenos Dias!</value>
      </property>
   </bean>
</beans>

The XML file in listing 1.3 declares an instance of a GreetingServiceImpl in the Spring container and configures its greeting property with a value of "Buenos Dias!" Let's dig into the details of this XML file a bit to understand how it works.

At the root of this simple XML file is the <beans> element, which is the root element of any Spring configuration file. The <bean> element is used to tell the Spring container about a class and how it should be configured. Here, the id attribute is used to name the bean greetingService and the class attribute specifies the bean's fully qualified class name.

Within the <bean> element, the <property> element is used to set a property, in this case the greeting property. By using <property>, we're telling the Spring container to call setGreeting() when setting the property.

The value of the greeting is defined within the <value> element. Here we've given the example a Spanish flair by choosing "Buenos Dias" instead of the traditional "Hello World."

The following snippet of code illustrates roughly what the container does when instantiating the greeting service based on the XML definition in listing 1.3:2

GreetingServiceImpl greetingService = new GreetingServiceImpl();
greetingService.setGreeting("Buenos Dias!");

Similarly, we may choose to have Spring set the greeting property through GreetingServiceImpl's single argument constructor. For example:

<bean id="greetingService"
      class="com.springinaction.chapter01.hello.GreetingServiceImpl">
   <constructor-arg>
      <value>Buenos Dias!</value>
   </constructor-arg>
</bean>

The following code illustrates how the container will instantiate the greeting service when using the <constructor-arg> element:

GreetingServiceImpl greetingService =
   new GreetingServiceImpl("Buenos Dias");

The last piece of the puzzle is the class that loads the Spring container and uses it to retrieve the greeting service. Listing 1.4 shows this class.

Listing 1.4 The Hello World main class

package com.springinaction.chapter01.hello;
 
import java.io.FileInputStream;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
 
public class HelloApp {
   public static void main(String[] args) throws Exception {
      BeanFactory factory =
         new XmlBeanFactory(new FileInputStream("hello.xml"));
 
      GreetingService greetingService =
         (GreetingService) factory.getBean("greetingService");
 
      greetingService.sayGreeting();
   }
}

Wednesday, April 2, 2008

12 BENEFITS of Spring MVC over Struts

1. Spring provides a very clean division between controllers, JavaBean models, and views.

2. Spring’s MVC is very flexible. Unlike Struts, which forces your Action and Form objects into concrete inheritance (thus taking away your single shot at concrete inheritance in Java), Spring MVC is entirely based on interfaces. Furthermore, just about every part of the Spring MVC framework is configurable via plugging in your own interface. Of course we also provide convenience classes as an implementation option.

3. Spring, like WebWork, provides interceptors as well as controllers, making it easy to factor out behavior common to the handling of many requests.

4. Spring MVC is truly view-agnostic. You don’t get pushed to use JSP if you don’t want to; you can use Velocity, XLST or other view technologies. If you want to use a custom view mechanism - for example, your own templating language - you can easily implement the Spring View interface to integrate it.

5. Spring Controllers are configured via IoC like any other objects. This makes them easy to test, and beautifully integrated with other objects managed by Spring.

6. Spring MVC web tiers are typically easier to test than Struts web tiers, due to the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet.

7. The web tier becomes a thin layer on top of a business object layer. This encourages good practice. Struts and other dedicated web frameworks leave you on your own in implementing your business objects; Spring provides an integrated framework for all tiers of your application.

8. No ActionForms. Bind directly to domain objects

9. More testable code (validation has no dependency on Servlet API)

10. Struts imposes dependencies on your Controllers (they must extend a Struts class), Spring doesn’t force you to do this although there are convenience Controller implementations that you can choose to extend.

11. Spring has a well defined interface to business layer

12. Spring offers better integration with view technologies other than JSP (Velocity / XSLT / FreeMarker / XL etc.)

Introduction to AOP-Main Spring Framework Feature(Good Article,Easy to understand)

Introduction to AOP

2.1) The Real Problem

Since AOP is relatively new, this section devotes time in explaining the need for Aspect Oriented Programming and the various terminologies that are used within. Let us look into the traditional model of before explaining the various concepts.

Consider the following sample application,

Account.java

                               
public class Account{
 
    public long deposit(long depositAmount){  
 
        newAmount = existingAccount + depositAccount;
        currentAmount = newAmount;
        return currentAmount;
 
    }
 
    public long withdraw(long withdrawalAmount){
 
        if (withdrawalAmount <= currentAmount){
            currentAmount = currentAmount – withdrawalAmount;
        }
        return currentAmount;
 
    }   
}
                               

The above code models a simple Account Object that provides services for deposit and withdrawal operation in the form of Account.deposit() and Account.withdraw() methods. Suppose say we want to add some bit of the security to the Account class, telling that only users with BankAdmin privilege is allowed to do the operations. With this new requirement being added, let us see the modified class structure below.

Account.java

                               
public class Account{
 
    public long deposit(long depositAmount){         
 
        User user = getContext().getUser();
        if (user.getRole().equals("BankAdmin"){              
            newAmount = existingAccount + depositAccount;
            currentAmount = newAmount;
        }
        return currentAmount;
 
    }
 
    public long withdraw(long withdrawalAmount){
 
        User user = getContext().getUser();
        if (user.getRole().equals("BankAdmin"){
            if (withdrawalAmount <= currentAmount){
                currentAmount = currentAmount – withdrawalAmount;
            }
        }
        return currentAmount;
    }   
}
                              

Assume that getContext().getUser() someway gives the current User object who is invoking the operation. See the modified code mandates the use of adding additional if condition before performing the requested operation. Assume that another requirement for the above Account class is to provide some kind of Logging and Transaction Management Facility. Now the code expands as follows,

Account.java

                               
public class Account{
 
    public long deposit(long depositAmount){         
 
        logger.info("Start of deposit method");
        Transaction trasaction  = getContext().getTransaction();
        transaction.begin();          
        try{
            User user = getContext().getUser();
            if (user.getRole().equals("BankAdmin"){          
                newAmount = existingAccount + depositAccount;
                currentAmount = newAmount;
            }
            transaction.commit();
        }catch(Exception exception){
            transaction.rollback();
        }
        logger.info("End of deposit method");
        return currentAmount;
 
    }
 
    public long withdraw(long withdrawalAmount){
 
        logger.info("Start of withdraw method");
        Transaction trasaction = getContext().getTransaction();
        transaction.begin();          
        try{
            User user = getContext().getUser();
            if (user.getRole().equals("BankAdmin"){
                if (withdrawalAmount <= currentAmount){
                    currentAmount = currentAmount – withdrawalAmount;
                }
            }
            transaction.commit();
        }catch(Exception exception){
            transaction.rollback();
        }
        logger.info("End of withdraw method");
        return currentAmount;
 
    }   
}
                               

The above code has so many dis-advantages. The very first thing is that as soon as new requirements are coming it is forcing the methods and the logic to change a lot which is against the Software Design. Remember every piece of newly added code has to undergo the Software Development Lifecycle of Development, Testing, Bug Fixing, Development, Testing, .... This, certainly cannot be encouraged in particularly big projects where a single line of code may have multiple dependencies between other Components or other Modules in the Project.

2.2) The Solution through AOP

Let us re-visit the Class Structure and the Implementation to reveal the facts. The Account class provides services for depositing and withdrawing the amount. But when you look into the implementation of these services, you can find that apart from the normal business logic, it is doing so many other stuffs like Logging, User Checking and Transaction Management. See the pseudo-code below that explains this.

 

 

 

 

                               
public void deposit(){
 
    // Transaction Management
    // Logging
    // Checking for the Privileged User
    // Actual Deposit Logic comes here 
 
}
 
public void withdraw(){
 
    // Transaction Management
    // Logging
    // Checking for the Privileged User
    // Actual Withdraw Logic comes here 
 
}
                               

From the above pseudo-code, it is clear that Logging, Transaction Management and User Checking which are never part of the Deposit or the Service functionality are made to embed in the implementation for completeness. Specifically, AOP calls this kind of logic that cross-cuts or overlaps the existing business logic as Concerns or Cross-Cutting Concerns. The main idea of AOP is to isolate the cross-cutting concerns from the application code thereby modularizing them as a different entity. It doesn't mean that because the cross-cutting code has been externalized from the actual implementation, the implementation now doesn't get the required add-on functionalities. There are ways to specify some kind of relation between the original business code and the Concerns through some techniques which we will see in the subsequent sections.

3) AOP Terminologies

It is hard to get used with the AOP terminologies at first but a thorough reading of the following section along with the illustrated samples will make it easy. Let us look into the majorly used AOP jargons.

3.1) Aspects

An Aspect is a functionality or a feature that cross-cuts over objects. The addition of the functionality makes the code to Unit Test difficult because of its dependencies and the availability of the various components it is referring. For example, in the below example, Logging and Transaction Management are the aspects.

                               
public void businessOperation(BusinessData data){
 
    // Logging
    logger.info("Business Method Called");
 
    // Transaction Management Begin
    transaction.begin();
 
    // Do the original business operation here
 
    transaction.end();
}
                               

3.2) JoinPoint

Join Points defines the various Execution Points where an Aspect can be applied. For example, consider the following piece of code,

                               
public void someBusinessOperation(BusinessData data){
 
    //Method Start -> Possible aspect code here like logging.
 
    try{
        // Original Business Logic here.
    }catch(Exception exception){
        // Exception -> Aspect code here when some exception is raised.     
    }finally{
        // Finally -> Even possible to have aspect code at this point too.
    }
 
    // Method End -> Aspect code here in the end of a method.
}
                               

In the above code, we can see that it is possible to determine the various points in the execution of the program like Start of the Method, End of the Method, the Exception Block, the Finally Block where a particular piece of Aspect can be made to execute. Such Possible Execution Points in the Application code for embedding Aspects are called Join Points. It is not necessary that an Aspect should be applied to all the possible Join Points.

3.3) Pointcut

As mentioned earlier, Join Points refer to the Logical Points wherein a particular Aspect or a Set of Aspects can be applied. A Pointcut or a Pointcut Definition will exactly tell on which Join Points the Aspects will be applied. To make the understanding of this term clearer, consider the following piece of code,

                               
aspect LoggingAspect {}
aspect TransactionManagementAspect {}
                               

Assume that the above two declarations declare something of type Aspect. Now consider the following piece of code,

                               
public void someMethod(){
 
    //Method Start
 
    try{
        // Some Business Logic Code.
    }catch(Exception exception){
        // Exception handler Code
    }finally{
        // Finally Handler Code for cleaning resources.
    }
 
    // Method End
}
                               

In the above sample code, the possible execution points, i.e. Join Points, are the start of the method, end of the method, exception block and the finally block. These are the possible points wherein any of the aspects, Logging Aspect or Transaction Management Aspect can be applied. Now consider the following Point Cut definition,

                               
pointcut method_start_end_pointcut(){
 
    // This point cut applies the aspects, logging and transaction, before the 
    // beginning and the end of the method.
 
}
 
pointcut catch_and_finally_pointcut(){
 
    // This point cut applies the aspects, logging and transaction, in the catch 
    // block (whenever an exception raises) and the finally block.
 
}
                               

As clearly defined, it is possible to define a Point Cut that binds the Aspect to a particular Join Point or some Set of Join Points.

3.4) Advice

Now that we are clear with the terms like Aspects, Point Cuts and Join Points, let us look into what actually Advice is. To put simple, Advice is the code that implements the Aspect. In general, an Aspect defines the functionality in a more abstract manner. But, it is this Advice that provides a Concrete code Implementation for the Aspect.

Thursday, March 27, 2008

Simplify Spring 2.5 MVC configuration with Java annotations.

Simplify Spring 2.5 MVC configuration with Java annotations.

 

Steps:

            Use @Controller to make class to handler web request

            Use @RequestMapping to map with Url

 

Here is the code that maps url pattern with method.

 

 

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
    
@Controller
public class SimpleController {
    
    @RequestMapping("/index.html")
    public void indexHandler() {
    }
    
    @RequestMapping("/about.html")
    public void aboutHandler() {
    }
    
    @RequestMapping("/admin.html")
    public void adminHandler() {
    }

 

How to create Immutable Objects

A Strategy for Defining Immutable Objects

 

 

·  Don't provide "setter" methods — methods that modify fields or objects referred to by fields.

·  Make all fields final and private.

·  Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.

 

Eg Code here:

 
final public class ImmutableRGB {
 
    //Values must be between 0 and 255.
    final private int red;
    final private int green;
    final private int blue;
    final private String name;
 
    public ImmutableRGB(int red, int green, int blue, String name) {
        check(red, green, blue);
        this.red = red;
        this.green = green;
        this.blue = blue;
        this.name = name;
    }
    public int getRGB() {
        return ((red << 16) | (green << 8) | blue);
    }
    public String getName() {
        return name;
    }
}