Saturday, 22 July 2017

Singleton Design Pattern


package com.help4j.advance.pattern;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;

/**
 * @author aklahoti
 *
 */
public class Singleton implements Serializable, Cloneable{

 public static void main(String[] args) throws CloneNotSupportedException, FileNotFoundException, IOException, ClassNotFoundException, InstantiationException, IllegalAccessException{
  
  // Test creating an object of Singleton Class
  Singleton obj = Singleton.getInstance();
  System.out.println(obj);
  
  // Test serialzation/deserialization of singleton object. It should not create new object and return same object.
  ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("resources/singleton.ser"));
  os.writeObject(obj);
  ObjectInputStream is = new ObjectInputStream(new FileInputStream("resources/singleton.ser"));
  Singleton deserObj = (Singleton) is.readObject();
  System.out.println("***Deserialized Singleton Object***");
  System.out.println(deserObj);
  
  // Test cloning of singleton object.  It should not create new object and return same object.
  Singleton cloneObj = (Singleton) obj.clone();
  System.out.println("***Cloned Singleton Object***");
  System.out.println(cloneObj);
  
  // Test reflexion of singleton object. It should throw exception.
  Class<Singleton> classObj = (Class<Singleton>) Class.forName("com.java.test.pattern.Singleton");
  System.out.println(classObj.newInstance());
  
 }
 private static final long serialVersionUID = 1L;

 private static Singleton instance = null;
 
 private static Object DUMMY_OBJECT = new Object();
 
 private Singleton(){
  /*To prevent object creation using reflection*/
  if(instance!=null){
   throw new InstantiationError( "Singleton Object is already created." );
  }
 }
 
 public static Singleton getInstance(){
  /*Double checked locking*/
  if(instance == null){
   synchronized (DUMMY_OBJECT) {
    if(instance == null){
     instance = new Singleton();
    }
   }
  }
  return instance;
 }
 
 public static void print(){
  System.out.println("I am a singleton class.");
 }
 
 /*To prevent object creation using deserialization*/
 private Object readResolve() throws ObjectStreamException{
  return instance;
 }
 
 /*To prevent object creation using cloning*/
 @Override
 protected Object clone() throws CloneNotSupportedException {
  return instance;
 }
}

Sunday, 26 March 2017

Spring Interview Questions

Spring Bean Life Cycle

  1.  Default constructor will be called.
  2.  All properties setter methods will be called.
  3.  If class implements BeanNameAware then setBeanName method will be called.
  4.  If class implements BeanFactoryAware then setBeanFactory method will be called.
  5.  If class implements ApplicationContextAware then setApplicationContext method will be called.
  6.  If class implements BeanPostProcessor then its postProcessBeforeInitialization will be called.
  7.  If class implements InitializingBean then afterPropertiesSet method will be called.
  8.  If class has custom init method defined then it will be called.
  9.  If class implements BeanPostProcessor then its postProcessAfterInitializationwill be called.
  10.  If class implements DisposableBean then destroy method will be called.
  11.  If class has custom destroy method defined then it will be called. 
Spring MVC flow


1. Dipatcher Servlet which is also know as front controller of Spring application handles all the request mapped to it in web.xml and ask for appropriate controller from Handler Mapping

2. Handler Mapping is a configuration for url and controller mapping. It look for controller:

Popular Implentations of HandlerMapping:

BeanNameUrlHandlerMapping - This is a default spring handler mapping. Name of bean considered as URL.


<bean name="/welcome.htm" class="com.help4j.controller.WelcomeController" />

SimpleUrlHandlerMapping - Map with key value pair of URL and controller bean name.

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
   <property name="mappings">
  <props>
     <prop key="/welcome.htm">welcomeController</prop>
   </props>
   </property>
</bean>

<bean id="welcomeController" class="com.help4j.controller.WelcomeController" />


DefaultAnnotationHandlerMapping - Annotation based @RequestMapping at class and method level.
WelcomeController.java
package com.help4j.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/welcome")
public class WelcomeController{

 @RequestMapping(method = RequestMethod.GET)
 public ModelAndView helloWorld(){

  ModelAndView model = new ModelAndView("WelcomePage");
  model.addObject("msg", "hello world");

  return model;
 }
}


3. Controller calls service layer to execute business logic and retrurn ModelAndView, which is wrapper for model object and view name.

Popular Controller Types:

AbstractController
AbstractCommandController
SimpleFormController


4. View Resolver look for appropriate view JSP/HTML based on view name and return to user.

Popular Implentations of ViewResolver:

InternalResourceViewResolver