Tuesday, April 8, 2014

Spring Core : Explanation of few very important meta data and their properties

Spring is a container-based framework. But if you don’t configure Spring, then it’s an empty container and doesn’t serve much purpose. Programming by exception - the common jingle for Java EE developer right?

So we need to configure Spring to tell what beans it should contain and how to wire those beans so that they can work together. As of Spring 3.0, there are two ways to configure beans in the Spring container. Traditionally, Spring configuration is defined in one or more XML files. But Spring 3.0 also offers a Java-based configuration option. but here i will focus on the traditional XML option.

Spring comes with several XML name-spaces through which you can configure the spring container. Among those beans, aop, context, mvc, oxm, jee and tx are the most frequent used name-spaces in an application. Let see those name-spaces and their properties :


1. beans : The core primitive spring name-space, enabling declaration of beans and how they should be wired.  
         Attributes of a bean:
          
         a. id: Represents how a bean should be referred by the client application.
         b. class: Tells which class a bean points to.
         c. constructor-arg: The element is used to give Spring additional information to use when constructing a bean. If no arguments are given, the default constructor is used.
         d. factory-method: Lets you specify a static method to be invoked instead of the constructor to create an instance of a class. This attribute will allow you to achieve exactly the same thing.
         e. scope: By default, all Spring beans are singletons. This attribute lets you declare the scope of a bean without hard coding the scoping rules in the bean class itself. A scope of a bean might be:
                e.1. singleton(Spring’s singleton beans only guarantee a single instance of the bean definition per the application context)
                e.2. prototype
                e.3. request
                e.4. session
                e.5. global-session
         
         f. init-method: The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation.
         g. destroy-method: destroy-method specifies a method that is called just before a bean is removed from the container.
         h. property: Bean properties can be configured in Spring using this element. Instead of injecting values through a constructor argument, injects by calling a property’s setter method.
                

   
   
      
      
      
   

Note that the value attribute is used exactly the same when setting a numeric value as it is when setting a String value. Spring will determine the correct type for the value based on the property’s type.
      
            
                  
                        
                        
                        
                        
                  
            
      
Just because a property is a java.util.Set, that doesn’t mean that you must use to do the wiring. Even though it may seem odd to configure a java.util.List property using , it’s certainly possible. In doing so, you’ll be guaranteed that all members of the List will be unique. In case of Map, the declaration would be:
  
      
            
                  
                        
                        
                        
                  
              
       

      i. primary & auto-wire-candidate: The primary attribute is only useful for identifying a preferred autowire candidate. If you’d rather eliminate some beans from consideration when auto-wiring, then you can set their auto-wire-candidate attribute to false.

2. context:  The context schema deals with ApplicationContext configuration with the help of its other elements. The elements that context does have are annotation-config, property-placeholder, component-scan, load-time-weaver, spring-configured, mbean-export.


      a. context:annotation-config: tells Spring that you intend to use annotation-based wiring in Spring. Once it’s in place you can start annotating your code to indicate that spring should automatically wire values into properties, methods, and constructors.
       
      b. property-placeholer: This element activates the replacement of ${...} placeholders, resolved against the specified properties file (as a Spring resource location). This element is a convenience mechanism that sets up a PropertyPlaceholderConfigurer for you; if you need more control over the PropertyPlaceholderConfigurer, just define one yourself explicitly. For example follow the configuration below:


      


      
            
            
            
             
      

The actual values come from another file in the standard Java Properties format:


jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://production:9002
jdbc.username=sa
jdbc.password=root

      c. context:component-scan: The element does everything that does, plus it configures Spring to automatically discover beans and declare them for you. What this means is that most (or all) of the beans in your Spring application can be declared and wired without using in your spring configuration file. By default, looks for classes that are annotated with one of a handful of special stereotype annotations: 

            1.@Component—A general-purpose stereotype annotation indicating that the class is a Spring component. 
            2.@Controller—Indicates that the class defines a Spring MVC controller.
            3.@Repository—Indicates that the class defines a data repository. 
            4.@Service—Indicates that the class defines a service. 
            5.Any custom annotation that is itself annotated with @Component. 
  
      d. load-time-wevaer: Registers an AspectJ load-time weaver.
      e. mbean-export: Exports beans as JMX MBeans.  
      f. spring-configured: Enables injection into objects that are not instantiated by Spring. 

3. jee: The JEE namespace provides configuration elements for looking up objects from JNDI as well as wiring references to EJBs into a Spring context.    
      a. jndi-environment: Defines environment settings for JNDI lookups.        
      b. jndi-lookup: Declares a reference to an object to be retrieved from JNDI.
      c. local-slsb: Declares a reference to a local stateless session EJB.
      d. remote-slsb: Declares a reference to a remote stateless session EJB.

 4. tx: The "tx" namespace provides support for declarative transactions across beans declared in Spring.
       
       a. advice: Declares transactional advice.
       b. annotation-driven: Tells Spring to use the @Transactional annotation for transactional rules.
       c.  attributes: Declares transactional rules for one or more methods.
       d. jta-transaction-manager: Configures a JTA transaction manager, automatically detecting WebLogic, WebSphere, or OC4J.
       e. method: Describes transactional rules for a given method signature.

5. mvc:

          a. annotation-driven: The tag packs a punch. It registers several features, including JSR-303 validation support, message conversion and support for field formatting.
          b. resources:  Configures a handler for serving static resources such as images, js, and, css files with cache headers optimized for efficient loading in a web browser. Allows resources to be served out of any path that is reachable via Spring's Resource handling.
          c. default-servlet-handler:  Configures a handler for serving static resources by forwarding to the Servlet container's default Servlet. Use of this handler allows using a "/" mapping with the Dispatcher Servlet while still utilizing the Servlet container to serve static resources.
          d. interceptors:  The ordered set of interceptors that intercept HTTP Servlet Requests handled by Controllers. Interceptors allow requests to be pre/post processed before/after handling. Each inteceptor must implement the org.springframework.web.servlet.HandlerInterceptor or org.springframework.web.context.request.WebRequestInterceptor interface. The interceptors in this set are automatically configured on each registered HandlerMapping. The URI paths each interceptor applies to are configurable.
          e. view-controller: The name of the view to render. If not specified, the view name will be determined from the current HttpServletRequest by the DispatcherServlet's  RequestToViewNameTranslator.

6. oxm:

          a. jaxb2-marshaller:
          b. class-to-be-bound

Boring right! But the guys who have experience in Spring or the guys who like to start working in Spring will soon realize that spending time to learn Spring configuration is a good investment. Enjoy!!
Reference: manning-spring-in-action( 3rd edition )

Saturday, August 3, 2013

Singleton pattern : The Good, Better and Best ways of implementation

In software industry the term "singleton" is associated with design pattern. It is mainly used when you need a single instance of a class to coordinate actions across the system. For instance, in the database driven applications you never want to request DB to open a connection for each subsequent operations. Instead you want to open only one connection during the first request and the next subsequent requests will use that connection to perform DB operations. To serve this purpose singleton pattern is quite handy. For having the deeper understanding of this pattern, you just need to have the knowledge of "static" construct and a basic knowledge on threading.
The good:
public class SingletonObject
{
    private SingletonObject()
    {
    }

    public static SingletonObject getSingletonObject()
    {
      if (ref == null) {
         synchronized (SingletonObject .class) {
            ref = new SingletonObject();
         }
      } 
      return ref;
    }

    private static volatile SingletonObject ref;
}
The good ++:
public class SingletonObject
{
    private SingletonObject()
    {
        // no code req'd
    }

    public static SingletonObject getSingletonObject()
    {
      return ref;
    }

    private static final SingletonObject ref = new SingletonObject();
}
The better: This technique doesn't require any special language constructs. So on that point of view this is better!
public class Singleton {
       // Private constructor prevents instantiation from other classes
       private Singleton() { }
 
       /**
        * SingletonHolder is loaded on the first execution of Singleton.
        * getInstance() or the first access to SingletonHolder.INSTANCE, 
        * not before.
        */
        private static class SingletonHolder { 
                public static final Singleton INSTANCE = new Singleton();
        }
 
        public static Singleton getInstance() {
                return SingletonHolder.INSTANCE;
        }
}
The best:
public enum SingletonObject { 
    INSTANCE;
}
According to Joshua Bloch:"a single-element enum type is the best way to implement a singleton for any version of Java that supports enum. This is concise and has no drawbacks regarding serializable objects which is challenging for other implementations.

Saturday, July 20, 2013

Inheritence : The order of execution

This post is especially targeted for that people who doesn't have any OOP concept ? :) oh no i am kidding. Ok, this post will discuss about the inheritance and its order of execution. Inheritance makes life easier and a very powerful channel to introduce the dynamic nature of polymorphism in your application. Sometimes people can get crazy if they don't know the actual order of execution of inheritance. Don't worry, i am sure this post will help you to remove your confusion in an easy way. Have a look at the following snippet. For better understanding of the reader it has been written in Java.

public class ClassE {

    static int superInt = superIntMethod(); 
    static int superIntMethod(){
        System.out.println("1-Initializing static super int");
        return 1;
    }
    static {
        System.out.println("2-Executing super static block"); /* static initialization block */ 
    }
   
    static int superInstanceIntMethod() {
        System.out.println("5-Initialzing superInstanceInt");
        return 3;
    }
   
    private int superInstanceInt=superInstanceIntMethod();
   
    ClassE(){
        System.out.println("7-Running ClassE constructor");
    }
   
    {
        System.out.println("6-Running super object initialization block");
    }
    public static void main(String[] args) {
        new SubClass();

    }

}

class SubClass extends ClassE {
    static int subInt = subIntMethod();
    static int subIntMethod(){
        System.out.println("3-Initializing static sub int");
        return 2;
    }
   
    static {
        System.out.println("4-Executing sub static block"); /* static initialization block */ 
    }

   
    static int subInstanceIntMethod() {
        System.out.println("9-Initialzing subInstanceInt");
        return 3;
    }
    SubClass(){
        System.out.println("10-Running SubClass constructor");
    }
    {
        System.out.println("8-Running sub object initialization block"); /* object initialization block */ 
    }
   
   
    private int subInstanceInt = subInstanceIntMethod();
       
}

Just run it from your IDE and observe the output. Then match each line of output with this code. Enjoy :) .

     

Friday, August 10, 2012

Polymorphism in php

You are very happy to hear that PHP supports OOP and decided to spend your holiday by exploring the Object Oriented Feature of  PHP. But suddenly you got stuck to write method overloading and also became furious  for the absence of  Late static binding(Lazy Binding).But don't be worried, the later would be solved in PHP v6 and now a little example how we can achieve method overloading in PHP.


class overloading
{

   function __call($method, $args)
   {

      if($method == 'talk') {
         if(count($args) == 0) {
            $this->sayNothing();
         }
         elseif(count($args) == 1) {
            if(is_array($args[0])) {
               $this->sayArray($args[0]);
            }
            else {
               $this->saySentence($args[0]);
            }
         }
         elseif(count($args) == 2) {
            $this->sayTwo($args[0], $args[1]);
         }
         else {
            return false;
         }
      }
   }

   public function function rawr()
   {
      echo "rawr";
   }

   protected function sayArray($arr)
   {
      foreach($arr as $s) {
         $this->saySentence($s .". ");
      }
   }

   protected function sayNothing()
   {
      echo "I have nothing to say.";
   }

   protected function saySentence($sentence)
   {
      echo $sentence;
   }

   protected function sayTwo($first,$second)
   {
      echo $first . ".
;" . $second . ".";
   }

}

$o = new overloading();
$o->rawr();
$o->talk('a sentence');
$o->talk('a sentence','another sentence');
$o->talk(array('hello I am joey.','nice to meet you'));

Like to explore something new in PHP?

Few months i worked in a Django project.Oh!!!!! Introspection and Introspection, simply gave me some kind of madness for python.I really observed the super power of it through out the project and couldn't tie myself to write something about it.Introspection is a conscious and purposive process relying on thinking, reasoning, and examining one's own thoughts, feelings, and, in more spiritual cases, one's soul  and this what exactly Introspection is.If you give access to read thoughts of one class then you are done!!!!!!Now what you have to do is just put a mirror in front of the class.PHP took few more time to discover this mirror :).  It is, in this rail from its 5 and 5+ version.

In PHP, this can be achieved simply by using the delegation design pattern.You can explore the following code snippet, then close your eyes and think how could you use this power to enrich and boost the execution time.



class ClassOne {

   function callClassOne() {

      print "In Class One\n";

   }

}

class ClassTwo {

    function callClassTwo() {

       print "In Class Two\n";

    }

}

class ClassOneDelegator {

   private $targets;

   function __construct() {

      $this->target[] = new ClassOne();

   }

   function addObject($obj) {

      $this->target[] = $obj;   //Register your object for Introspect

   }

   function __call($name, $args) {

      //the magic method of  PHP again rocks in this case

      foreach ($this->target as $obj) {

         $r = new ReflectionClass($obj);

         if($r->hasMethod($name)) {

            if ($method = $r->getMethod($name)) {

               if ($method->isPublic() && !$method->isAbstract()) {

                  return $method->invoke($obj, $args);

               }

            }

         }

      }

   }

}
Testing the snipplet:
$obj = new ClassOneDelegator();

$obj->addObject(new ClassTwo());

$obj->callClassOne();

$obj->callClassTwo();
Enjoy your time and never forget "Work should be fun" :D.

SyntaxHighlighter