What are the design pattern available in Spring framework?

Spring Design Patterns
1. MVC - The advantage with Spring MVC is that your controllers are POJOs as opposed to being servlets. This makes for easier testing of controllers.

2. Front controller - Spring provides "DispatcherServlet" to ensure an incoming request gets dispatched to your controllers.

3. View Helper - Spring has a number of custom JSP tags, and velocity macros, to assist in separating code from presentation in views.

4. Singleton - Beans defined in spring config files are singletons by default.

5. Prototype - Instance type can be prototype.

6. Factory - Used for loading beans through BeanFactory and Application context.

7. Builder - Spring provides programmatic means of constructing BeanDefinitions using the builder pattern through Class "BeanDefinitionBuilder".

8. Template - Used extensively to deal with boilerplate repeated code (such as closing connections cleanly, etc..). For example JdbcTemplate.

9. Proxy - Used in AOP & Remoting.

10. DI/IOC - It is central to the whole BeanFactory/ApplicationContext stuff.

Spring Framework implemented on the layered architecture implements a good number of patterns; lets see them:

Creational Pattens
Singleton – This must be simplest but may be misused in multi-threaded programs; Spring Framework implements this pattern as part of bean scoping.
Example:
<bean id=”car” class=”com.acme.springexamples.domain.Car” scope="singleton”/>

Prototype – This is about creating or cloning a new instance whenever required; Spring Framework implements this pattern as part of bean scoping.
Example:
<bean id=”car” class=”com.acme.springexamples.domain.Car” scope="prototype”/>

Behavioural Patterns
Template – This pattern is about defining the skeleton of the algorithm in which some of the steps of the algorithm are deferred to the sub-classes or to the
data member objects. Spring framework implemented this pattern for variety of features like, JmsTemplate, JDBCTemplate.
Example:
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" scope="prototype">
<constructor-arg ref="dataSource" />
</bean>
Mediator – Please jump to Front Controller.
Structural Patterns
Proxy – This pattern is useful to control the access to an object and expose the same interface as that of that object. Spring framework implements this
pattern in its AOP support.
Example:
<aop:config>
   <aop:aspect id="myAspect" ref="aBean">
      <aop:pointcut id="businessService"
         expression="execution(* com.xyz.myapp.service.*.*(..))"/>

      <!-- a before advice definition -->
      <aop:before pointcut-ref="businessService"
         method="doRequiredTask"/>

      <!-- an after advice definition -->
      <aop:after pointcut-ref="businessService"
         method="doRequiredTask"/>

      <!-- an after-returning advice definition -->
      <!--The doRequiredTask method must have parameter named retVal -->
      <aop:after-returning pointcut-ref="businessService"
         returning="retVal"
         method="doRequiredTask"/>

      <!-- an after-throwing advice definition -->
      <!--The doRequiredTask method must have parameter named ex -->
      <aop:after-throwing pointcut-ref="businessService"
         throwing="ex"
         method="doRequiredTask"/>

      <!-- an around advice definition -->
      <aop:around pointcut-ref="businessService"
         method="doRequiredTask"/>
   ...
   </aop:aspect>
</aop:config>

<bean id="aBean" class="...">
...
</bean>
J2EE Patterns
Front Controller – this pattern is used to define a single point of entry for a server to handle incoming request; Spring framework implements this pattern
in its MVC module, as a servlet.
DAO Pattern – this pattern is about abstracting the database access. This patten is implemented in Spring framework in its DAO module.
Example:
<bean id="abstractJdbcDao" abstract="true" class="org.springframework.jdbc.core.support.JdbcDaoSupport">
<property name="dataSource" ref="dataSource"/>
</bean>
Design Principles:
IoC/DI – Entire framework is based on this design principle.

What is the difference between Setter injection and Constructor injection?


Setter Injection
Constructor Injection
1. In Setter Injection, partial injection of dependencies can possible, means if we have 3 dependencies like int, string, long, then its not necessary to inject all values if we use setter injection. If you are not inject it will takes default values for those primitives
1. In constructor injection, partial injection of dependencies cannot possible, because for calling constructor we must pass all the arguments right, if not so we may get error
2. Setter Injection will overrides the constructor injection value, provided if we write setter and constructor injection for the same property [i already told regarding this, hope you remember]
2. But, constructor injection cannot overrides the setter injected values
3. If we have more dependencies for example 15 to 20 are there in our bean class then, in this case setter injection is not recommended as we need to write almost 20 setters right, bean length will increase.
3. In this case, Constructor injection is highly recommended, as we can inject all the dependencies with in 3 to 4 lines [i mean, by calling one constructor]
4. Setter injection makes bean class object as mutable [We can change ]
4. Constructor injection makes bean class object as immutable [We cannot change ]

There are many key differences between constructor injection and setter injection.

  1. Partial dependency: can be injected using setter injection but it is not possible by constructor. Suppose there are 3 properties in a class, having 3 arg constructor and setters methods. In such case, if you want to pass information for only one property, it is possible by setter method only.
  2. Overriding: Setter injection overrides the constructor injection. If we use both constructor and setter injection, IOC container will use the setter injection.
  3. Changes: We can easily change the value by setter injection. It doesn't create a new bean instance always like constructor. So setter injection is flexible than constructor injection.

How can we assign multiple values to a single key in HashMap?

HashMap can be used to store values in key-value pair format, but some times you might be want store multiple values for the same key like
for key A, you want to store Apple and America
for key B, you want to store Bat and Bangladesh
for key C, you want to store Cat and China
the following code snippet will show how to store multiple values for the same key.

HashMap-single key multiple values using LIST

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SingleKeyMultipleValuesUsingList
{
public static void main(String[] args)
{
// create map to store
Map<String, List<String>> map = new HashMap<String, List<String>>();

               // create list one and store values
List<String> l1 = new ArrayList<String>();
l1.add("Apple");
l1.add("America");

               // create list two and store values
List<String> l2 = new ArrayList<String>();
l2.add("Bat");
l2.add("Bangladesh");

               // create list three and store values
List<String> l3 = new ArrayList<String>();
l3.add("Cat");
l3.add("China");

               // put values into map
map.put("A", l1);
map.put("B", l2);
map.put("C", l3);

               // iterate and display values
System.out.println("Fetching Keys and corresponding MULTIPLE Values n");
for (Map.Entry<String, List<String>> entry : map.entrySet())
{
String key = entry.getKey();
List<String> values = entry.getValue();
System.out.println("Key = " + key);
System.out.println("Values = " + values + "/n");
}
}
}

HashMap-single key multiple values using Collections

Which is the best one from the following i.e List l =new ArrayList() and ArrayList al=new ArrayList()

The First one List l = new ArrayList() 
allows you to use the List1 to refer to any object that is a sub class of list 


The second one ArrayList al = new ArrayList() 
will allow you to refer to only object that is an ArrayList Object

Logically the second way should be faster. But, since the binding happens 
at runtime, it shouldnt matter really. Its actually more to do with 
polymorphism. When you know you are going to be referencing object that may 
be sub classes and want to reuse the object ref.

It's simple, List is a Interface and "Arraylist, LinkedList, Vector" are your implementation. Each one with its own benefit, when you use the List any moment you can change your implementation, your application becomes more flexible. 

Example: 
List list = new ArrayLista(); 
for(String s : list){ 
... 


list = new LinkedList(); 
for(String s : list){ 
... 

What are the advantage of generics?

Generics was introduced in JAVA 5 version.
It has the following advantages

  1. Stronger type checks at compile time:-
    A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing run-time errors, which can be difficult to find.                                                                                                                                         
  2. Elimination of casting:-
    The following code snippet requires casting due to absence of  generics
    List list = new ArrayList();
    list.add("hello");
    String s = (String) list.get(0);//type casting
    
    with generics, the code does not require type casting
    List<String> list = new ArrayList<String>();
    list.add("hello");
    String s = list.get(0);   // no need of casting                        
  3. Enabling programmer to implement generic algorithm:-
         Which can be
         Generic CLASS declaration
         Generic INTERFACE declaration
         Generic METHOD declaration
         Generic CONSTRUCTOR declaration

Telephonic interview questions3 on java

12th Feb 2014
               Today, I have done another Telephonic interview round with one more client. Almost it took 21 Minutes duration. The following questions which are faced by myself. I hope that these will be very useful to my blog readers(i.e you).

  1. How can we call a constructor from another constructor in a single class?
  2. How can we sort the collection objects?
  3. To print the objects in DESCENDING order which interface or collection i need to be used?
  4. What is the DEFAULT sorting order of collections?
  5. When shall we go for SET or MAP? Explain.
  6. When shall we go for TREEset or TREEmap? Explain.
  7. While implementing sorting logic in HASHMAP, on which basis you will be sort i.e based on keys or values?
  8. What is lazyloading?(in Hibernate)
  9. Differentiate load() and get() methods in Hibernate.
  10. What are the available collections in Hibernate?
  11. can we write more than one catch bock for a try block?
  12. Below code will be compile or not?
             try
               {
                }
              catch(Exception e)
              {
                }
              catch(Null pointer Exception ne)
               {
                    }