Saturday, 24 August 2013

Java Interview Questions - Core Java, J2EE, Spring, HIbernate etc...

What is serialization?

If you serialize an object, then you must have the same class to deserialize it and use the object. If you modify the class then that can cause incompatibility and that can cause deserialization to fail. There are some changes you can make to a class that do not prevent deserialization, but some do.

Changes that affect deserialization
1.      Deleting an Instance Variable.
2.      Changing the type of an Instance Variable.
3.      Changing a non-transient variable to a transient variable.
4.      Moving a class up or down in hierarchy.
5.      Changing an Instance Variable to static.
6.      Changing class from serializable to non-serializable.
Changes that do not affect deserialization
1.      Changing transient variables to non-transient variables
2.      Changing the access level of an Instance Variable
3.      Create a new Instance Variable in a class.
Importance of SerialVersion UID

Each time the object is serialized, it is stamped with a version id of the object's class. This is called a serial version UID. When the object is deserialized, if the class has changed since serialization, then the class could have a different version id and deserialization fails.
But it can be controlled by the user. If there is any possibility that the class may undergo some changes, then put the serial version UID in the class.

When Java tries to deserialize an object, it compares the serialized object version UID with that of the class version UID that the JVM is using for deserialization. If two numbers do not match, then the JVM assumes that the class is not compatible for deserialization and it throws an exception.

So, the solution is to put the version UID in the class. Since the class may undergo changes, the version UID will remain the same and deserialization can be done easily.

How to get the Version UID for the class

Open a command prompt, got to the folder where your Java file is saved and type "serialver classname".

Which part of the memory is involved in Garbage Collection? Stack or Heap?

What is responsibility of Garbage Collector?
Garbage collector frees the memory occupied by the unreachable objects during the java program by deleting these unreachable objects.
It ensures that the available memory will be used efficiently, but does not guarantee that there will be sufficient memory for the program to run.
Is garbage collector a daemon thread?
Yes GC is a daemon thread. A daemon thread runs behind the application. It is started by JVM. The thread stops when all non-daemon threads stop.
Garbage Collector is controlled by whom?
The JVM controls the Garbage Collector; it decides when to run the Garbage Collector. JVM runs the Garbage Collector when it realizes that the memory is running low, but this behavior of JVM cannot be guaranteed.
One can request the Garbage Collection to happen from within the java program but there is no guarantee that this request will be taken care of by JVM.
When does an object become eligible for garbage collection?
An object becomes eligible for Garbage Collection when no live thread can access it.
What are the different ways to make an object eligible for Garbage Collection when it is no longer needed?
1.      Set all available object references to null once the purpose of creating the object is served :
public class GarbageCollnTest1 {

   public static void main (String [] args){
String str = "Set the object ref to null";
//String object referenced by variable str is not eligible for GC yet

str = null;
/*String object referenced by variable str becomes eligible for GC */


2.      Make the reference variable to refer to another object : Decouple the reference variable from the object and set it refer to another object, so the object which it was referring to before reassigning is eligible for Garbage Collection.

public class GarbageCollnTest2 {

   public static void main(String [] args){
String str1 = "Garbage collected after use";
String str2 = "Another String";
//String object referred by str1 is not eligible for GC yet

str1 = str2;
/* Now the str1 variable referes to the String object "Another String" and the object "Garbage collected after use" is not referred by any variable and hence is eligible for GC */



3) Creating Islands of Isolation: If you have two instance reference variables which are referring to the instances of the same class, and these two reference variables refer to each other and the objects referred by these reference variables do not have any other valid reference then these two objects are said to form an Island of Isolation and are eligible for Garbage Collection.

public class GCTest3 {
GCTest3 g;

   public static void main(String [] str){
GCTest3 gc1 = new GCTest3();
GCTest3 gc2 = new GCTest3();
gc1.g = gc2; //gc1 refers to gc2
gc2.g = gc1; //gc2 refers to gc1
gc1 = null;
gc2 = null;
//gc1 and gc2 refer to each other and have no other valid //references
//gc1 and gc2 form Island of Isolation
//gc1 and gc2 are eligible for Garbage collection here

Can the Garbage Collection be forced by any means?
No. The Garbage Collection cannot be forced, though there are few ways by which it can be requested there is no guarantee that these requests will be taken care of by JVM.
How can the Garbage Collection be requested?
There are two ways in which we can request the JVM to execute the Garbage Collection.
  • 1) The methods to perform the garbage collections are present in the Runtime class provided by java. The Runtime class is a Singleton for each java main program.
    The method getRuntime() returns a singleton instance of the Runtime class. The method gc() can be invoked using this instance of Runtime to request the garbage collection.
  • 2) Call the System class System.gc() method which will request the jvm to perform GC.

What is the purpose of overriding finalize() method?
The finalize() method should be overridden for an object to include the cleanup code or to dispose of the system resources that should to be done before the object is garbage collected.
If an object becomes eligible for Garbage Collection and its finalize() method has been called and inside this method the object becomes accessible by a live thread of execution and is not garbage collected. Later at some point the same object becomes eligible for Garbage collection, will the finalize() method be called again?
How many times does the garbage collector calls the finalize() method for an object?
What happens if an uncaught exception is thrown from during the execution of the finalize() method of an object?
The exception will be ignored and the garbage collection (finalization) of that object terminates.
What are different ways to call garbage collector?
Garbage collection can be invoked using System.gc() or Runtime.getRuntime().gc().
How to enable/disable call of finalize() method of exit of the application
Runtime.getRuntime().runFinalizersOnExit(boolean value) . Passing the boolean value will either disable or enable the finalize() call.
Why is Runtime.runFinalizersOnExit deprecated?

Because it is inherently unsafe. It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock. While this problem could be prevented if the class whose objects are being finalized were coded to "defend against" this call, most programmers do not defend against it. They assume that an object is dead at the time that its finalizer is called.
Further, the call is not "thread-safe" in the sense that it sets a VM-global flag. This forces every class with a finalizer to defend against the finalization of live objects!

What are different types of access modifiers in Java?
Accessible in the same package
Accessible in different package
Yes, only if the class extends the main class
What is the use of final keyword?
The final keyword can be assigned to
1.      Class level variable
2.      method
3.      class
4.      Objects
If a final is assigned to a variable, the variable behaves as a constant. It means that the value of variable once set cannot be changed.
final int i=1;
i =5; // error
If a final is assigned to a method then it cannot be overridden in its child class.
class Parent {
final void print(){
class Child extends Parent{
public final void print(){             // error cannot override final method

If a class is made as final, then no other class can extend it and make it as parent class. E.g. String Class.
Final objects are instantiated only once. i.e
final Map map = new HashMap();
map = new HashMap();  // error

What is use of synchronized keyword?
This keyword is used to prevent concurrency. Synchronized keyword can be applied to static/non-static methods or a block of code. Only one thread at a time can access synchronized methods and if there are multiple threads trying to access the same method then other threads have to wait for the execution of method by one thread. Synchronized keyword provides a lock on the object and thus prevents race condition. E.g.
public void synchronized method(){} 
public void synchronized staticmethod(){}
public void myMethod(){
            synchronized (this){             // synchronized keyword on block of  code

What is volatile keyword?
In general each thread has its own copy of variable, such that one thread is not concerned with the value of same variable in the other thread. But sometime this may not be the case. Consider a scenario in which the count variable is holding the number of times a method is called for a given class irrespective of any thread calling, in this case irrespective of thread access the count has to be increased. In this case the count variable is declared as volatile. The copy of volatile variable is stored in the main memory, so every time a thread access the variable even for reading purpose the local copy is updated each time from the main memory. The volatile variable also have performance issues.
What is a transient variable?
If some of the properties of a class are not required to be serialized then the variables are marked as transient. When an object is deserialized the transient variables retains the default value depending on the type of variable declared and hence lost its original value.
What is a strictfp modifier?
Strictfp is used with variable only . It is used to restrict floating point calculations ( fp ) to ensure portability ( platform Independent ). When this modifier is specified, the JVM adheres to the Java specifications ( IEEE-754 floating-point specification ) and returns the consistent value independent of the platform. That is, if you want the answers from your code (which uses floating point values) to be consistent in all platforms, then you need to specify the strictfp modifier.
What is a static variable?
Static keyword can be used with the variables and methods but not with the class but there are static class. Anything declared as static is related to class and not objects.
Static variable : Multiples objects of a class shares the same instance of a static variable. Consider the example:
public class Counter{
  private static int count=0;
 private int nonStaticcount=0;
  public void incrementCounter(){
  public int getCount(){
 return count;
 public int getNonStaticcount(){
 return nonStaticcount;
 public static void main(String args[]){
  Counter countObj1 = new Counter();
 Counter countObj2 = new Counter();
  System.out.println("Static count for Obj1: "+countObj1.getCount());
  System.out.println("NonStatic count for Obj1: "+countObj1.getNonStaticcount());
  System.out.println("Static count for Obj2: "+countObj2.getCount())
  System.out.println("NonStatic count for Obj2: "+countObj2.getNonStaticcount())

Static count for Obj1: 2
NonStatic count for Obj1: 2
Static count for Obj2: 2
NonStatic count for Obj2: 0
In the above program obj1 and obj2 share the same instance of static variable count hence if the value is incremented by one object , the incremented value will be reflected across the other objects.

What is a static method?
A method defined as static is called static method. A static method can be accessed without creating the objects. Just by using the Class name the method can be accessed.
Static method can only access static variables and not local or global non-static variables. For eg:
public class Test{
public static void printMe(){
System.out.println("Hello World");
public class MainClass{
 public static void main(String args[]){

Hello World
Why static methods cannot access non static variables or methods?
A static method cannot access non static variables or methods because static methods doesnt need the object to be accessed. So if a static method has non static variables or non static methods which has instantiated variables they will no be intialized since the object is not created and this could result in an error.
What is static class ?
A class cannot be declared static. But a class can be said a static class if all the variables and methods of the class are static and the constructor is private. Making the constructor private will prevent the class to be instantiated. So the only possibility to access is using Class name only
What is throw keyword?
Throw keyword is used to throw the exception manually. It is mainly used when the program fails to satisfy the given condition and it wants to warn the application. The exception thrown should be subclass of Throwable.

Why wait(), notify(), notifyAll() must be called inside a synchronized method/block?


his method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object.

Just to summarize we call wait (), notify () or notifyAll method in Java from synchronized method or synchronized block in Java to avoid:
1) IllegalMonitorStateException in Java which will occur if we don't call wait (), notify () or notifyAll () method from synchronized context.
2) Any potential race condition between wait and notify method in Java.

Difference between Wait and Sleep in Java


1)     Main difference between wait and sleep is that wait() method release the acquired monitor when thread is waiting while Thread.sleep() method keeps the lock or monitor even if thread is waiting
2)     wait method in java should be called from synchronized method or block while there is no such requirement for sleep() method.
3)     Thread.sleep() method is a static method and applies on current thread, while wait() is an instance specific method and only got wake up if some other thread calls notify method on same object.
4)     sleeping thread immediately goes to Runnable state after waking up while in case of wait, waiting thread first acquires the lock and then goes into Runnable state.
5)     wait is called on Object while sleep is called on Thread

Why wait, notify and notifyAll is declared in Object Class instead of Thread ?
Locks are made available on per Object basis, which is another reason wait and notify is declared in Object class rather then Thread class.

What is Blocking methods in Java
Blocking methods are those which blocks the current executing thread from further operation until function returns. So if you have just one thread in your program e.g. main thread and you call any blocking method e.g. reading from InputStream, your program will be blocked until reading of file finished.

public class BlcokingCallTest {

    public static void main(String args[]) throws FileNotFoundException, IOException  {
      System.out.println("Calling blocking method in Java");
      int input =;
      System.out.println("Blocking method is finished");

In this code example after executing first print statement your program will be blocked and will not execute second print statement until you enter some characters in console and press enter because read() method blocks until some input is available for reading.

Give some examples for java blocking methods
Most of the java I/O methods are blocking methods.

1) which blocks until input data is available, an exception is thrown or end of Stream is detected.
2) ServerSocket.accept() which listens for incoming socket connection in Java and blocks until a connection is made.
3) InvokeAndWait() wait until code is executed from Event Dispatcher thread.

Disadvantages of blocking method:

Blocking methods poses significant threat to scalability of System. Imagine you are writing a client server application and you can only serve one client at a time because your code blocks. there is no way you can make use of that System and its not even using resources properly because you might have high speed CPU sitting idle waiting for something.

Java5 addresses this issue by adding non blocking and asynchronous alternative of blocking IO calls and those utility can be used to write high performance
servers application in core Java.


Can an abstract class have a static method?
Yes an abstract class have a static method and it can be accessed by any other class(even not a concrete class).
Can an abstract class have a constructor?
Yes an abstract class have a default and parameterized constructors.
Why static methods cannot access non static variables or methods?
A static method cannot access non static variables or methods because static methods doesnt need the object to be accessed. So if a static method has non static variables or non static methods which has instantiated variables they will no be intialized since the object is not created and this could result in an error.

Why is main() method static?
To access the static method the object of the class is not needed. The method can be access directly with the help of ClassName. So when a program is started the JVM search for the class with main method and calls it without creating an object of the class.
What is the difference between static methods and instance methods?
Instance method belongs to the instance of a class therefore it requires an instance before it can be invoked, whereas static method belongs to the class itself and not to any class instance so it doesn’t need an instance to be invoked.
Instance methods use dynamic (late) binding, whereas static methods use static (early) binding.
When the JVM invokes a class instance method, it selects the method to invoke based on the type of the object reference, which is always known at run-time. On the other hand, when the JVM invokes a static method, it selects the method to invoke based on the actual class of the object, which may only be known at compile time.
Can static block throw exception?
Yes, static block can throw only Runtime exception or can use a try-catch block to catch checked exception.
Typically scenario will be if JDBC connection is created in static block and it fails then exception can be caught, logged and application can exit. If System.exit() is not done, then application may continue and next time if the class is referred JVM will throw NoClassDefFounderror since the class was not loaded by the Classloader.
What is difference between abstract class and interface?
1) A class is called abstract when it contains at least one abstract method. It can also contain n numbers of concrete method. Interface can contain only abstract ( non-implemented) methods.
2) The abstract class can have public, private, protect or default variables and also constants. In interface the variable is by default public final. In nutshell the interface doesn’t have any variables it only has constants.
3) A class can extend only one abstract class but a class can implement multiple interfaces.
4) If an interface is implemented it is compulsory to implement all of its methods but if an abstract class is extended it’s not compulsory to implement all methods.
5) The problem with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement that method in all of the classes which implement that interface. However, in the case of an abstract class, the method can be simply implemented in the abstract class and the same can be called by its subclass.
Explain with example to describe when to use abstract class and interface?
Consider a scenario where all Cars will have 4 tyres and other features can be different.
In this case any subclass of Car has to have 4 tyres. This is a case where abstract class will be used and a default implementation for tyres will be provided.
public abstract class Car{

public abstract String getCarName();

public final int getNoOfTyres(){
   return 4;

Consider a scenario where Cars can have any number of doors and other features can also be different. In this case interface will be created.
public interface Car{

public abstract String getCarName();
public abstract int getNoOfDoors();
Does java support multiple interitance? Why?
Java doesn’t support multiple inheritance but it provide a way through which it can enact it.
Consider the scenario is C++
Class A{

public void add(){
// some text

Class B{

public void add(){
// some text

Class C extends A,B{

public static void main(String arg[]){

C objC = new C();
objC.add(); // problem, compiler gets confused and cant
decide to call Class A or B method.

This problem is called Diamond problem.

This problem in java is taken care with the use of interfaces
In Java similar problem would look like:
Interface A{

interface B{

class C implements A,B{

// doesnt matter which interface it belong to
Can this keyword be assigned null value?
What are the different types of references in java?
Java has a more expressive system of reference than most other garbage-collected programming languages, which allows for special behavior for garbage collection. A normal reference in Java is known as a strong reference. The java.lang.ref package defines three other types of references—soft, weak, and phantom references. Each type of reference is designed for a specific use.
A SoftReference can be used to implement a cache. An object that is not reachable by a strong reference (that is, not strongly reachable), but is referenced by a soft reference is called softly reachable. A softly reachable object may be garbage collected at the discretion of the garbage collector. This generally means that softly reachable objects will only be garbage collected when free memory is low, but again, it is at the discretion of the garbage collector. Semantically, a soft reference means "keep this object unless the memory is needed."
A WeakReference is used to implement weak maps. An object that is not strongly or softly reachable, but is referenced by a weak reference is called weakly reachable. A weakly reachable object will be garbage collected during the next collection cycle. This behavior is used in the class java.util.WeakHashMap. A weak map allows the programmer to put key/value pairs in the map and not worry about the objects taking up memory when the key is no longer reachable anywhere else. Another possible application of weak references is the string intern pool. Semantically, a weak reference means "get rid of this object when nothing else references it."

A PhantomReference is used to reference objects that have been marked for garbage collection and have been finalized, but have not yet been reclaimed. An object that is not strongly, softly or weakly reachable, but is referenced by a phantom reference is called phantom reachable. This allows for more flexible cleanup than is possible with the finalization mechanism alone. Semantically, a phantom reference means "this object is no longer needed and has been finalized in preparation for being collected."

How to change the heap size of a JVM?
The old generation's default heap size can be overridden by using the -Xms and -Xmx switches to specify the initial and maximum sizes respectively:
java -Xms -Xmx program
For example:
java -Xms64m -Xmx128m program
What is difference between instanceof and isInstance(Object obj)?
Differences are as follows:
1) instanceof is a reserved word of Java, but isInstance(Object obj) is a method of java.lang.Class.
if (obj instanceof MyType) {
}else if (MyType.class.isInstance(obj)) {
2) instanceof is used of identify whether the object is type of a particular class or its subclass but isInstance(obj) is used to identify object of a particular class.

Java supports pass by value or pass by reference?
Java supports only pass by value. The arguments passed as a parameter to a method is mainly primitive data types or objects. For the data type the actual value is passed.
Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references.Java copies and passes the reference by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects.Consider the example:
 public void tricky(Point arg1, Point arg2)
   arg1.x = 100;
   arg1.y = 100;
   Point temp = arg1;
   arg1 = arg2;
   arg2 = temp;
 public static void main(String [] args)
   Point pnt1 = new Point(0,0);
   Point pnt2 = new Point(0,0);
   System.out.println("X: " + pnt1.x + " Y: " +pnt1.y);
   System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
   System.out.println(" ");
   System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
   System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);

X: 0 Y: 0
X: 0 Y: 0
X: 100 Y: 100
X: 0 Y: 0
The method successfully alters the value of pnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In the main() method, pnt1 and pnt2 are nothing more than object references. When you pass pnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references.

What is memory leak?
A memory leak is where an unreferenced object that will never be used again still hangs around in memory and doesnt get garbage collected.
What is the difference between equals() and ==?
== operator is used to compare the references of the objects.
public bollean equals(Object o) is the method provided by the Object class. The default implementation uses == operator to compare two objects.
But since the method can be overridden like for String class. equals () method can be used to compare the values of two objects.
 String str1 = "MyName";
 String str2 = "MyName";
 String str3 = str2;

 if(str1 == str2){
 System.out.println("Objects are equal")
 System.out.println("Objects are not equal")

 System.out.println("Objects are equal")
 System.out.println("Objects are not equal")


 Objects are not equal
 Objects are equal

 String str2 = "MyName";
 String str3 = str2;

 if(str2 == str3){
 System.out.println("Objects are equal")
 System.out.println("Objects are not equal")

 System.out.println("Objects are equal")
 System.out.println("Objects are not equal")

 Objects are equal
 Objects are equal

How to make sure that Childclass method actually overrides the method of the superclass?
The @Override annotation can be added to the javadoc for the new method. If you accidently miss an argument or capitalize the method name wrong, the compiler will generate a compile-time error.
How to find the size of an object?
The heap size of an object can be found using -
         Runtime.totalMemory()-Runtime.freeMemory() .

Spring  Questions

Explain DI or IOC pattern
Dependency injection is a way to achieve loose coupling. Inversion of control (IOC) relates to the way in which an object obtains references to its dependencies. This is often done by a lookup method. The advantage of inversion of control is that it decouples objects from specific lookup mechanisms and implementations of the objects it depends on. As a result, more flexibility is obtained for production applications as well as for testing.
Dependency injection (DI) is a programming design pattern and architectural model, sometimes also referred to as inversion of control or IOC, although technically speaking, dependency injection specifically refers to an implementation of a particular form of IOC. Dependency Injection describes the situation where one object uses a second object to provide a particular capacity. For example, being passed a database connection as an argument to the constructor method instead of creating one inside the constructor. The term "Dependency injection" is a misnomer, since it is not a dependency that is injected; rather it is a provider of some capability or resource that is injected. There are three common forms of dependency injection: setter, constructor and interface-based injection.
What are the advantages of spring framework? 
Spring has layered architecture. Use what you need and leave you don't need.
Spring Enables POJO Programming. There is no behind the scene magic here. POJO programming enables continuous integration and testability.
Dependency Injection and Inversion of Control Simplifies JDBC
Open source and no vendor lock-in.
Explain BeanFactory in spring
Bean factory is an implementation of the factory design pattern and its function is to create and dispense beans. As the bean factory knows about many objects within an application, it is able to create association between collaborating objects as they are instantiated. This removes the burden of configuration from the bean and the client. There are several implementation of BeanFactory. The most useful one is "org.springframework.beans.factory.xml.XmlBeanFactory" It loads its beans based on the definition contained in an XML file. To create an XmlBeanFactory, pass a InputStream to the constructor. The resource will provide the XML to the factory.
BeanFactory factory = new XmlBeanFactory(new FileInputStream("myBean.xml"));

This line tells the bean factory to read the bean definition from the XML file. The bean definition includes the description of beans and their properties. But the bean factory doesn't instantiate the bean yet. To retrieve a bean from a 'BeanFactory', the getBean() method is called. When getBean() method is called, factory will instantiate the bean and begin setting the bean's properties using dependency injection.

myBean bean1 = (myBean)factory.getBean("myBean");
Explain the role of ApplicationContext in spring
While Bean Factory is used for simple applications; the Application Context is spring's more advanced container. Like 'BeanFactory' it can be used to load bean definitions, wire beans together and dispense beans upon request. It also provide

1) A means for resolving text messages, including support for internationalization.
2) A generic way to load file resources.
3) Events to beans that are registered as listeners.

Because of additional functionality, 'Application Context' is preferred over a BeanFactory. Only when the resource is scarce like mobile devices, 'BeanFactory' is used. The three commonly used implementation of 'Application Context' are

1. ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application's classpath by using the code

ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");

2. FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code

ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");
What is AOP? How does it relate with IOC? What are different tools to utilize AOP?
Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns, or behaviour that cuts across the typical divisions of responsibility, such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviours affecting multiple classes into reusable modules. AOP and IOC are complementary technologies in that both apply a modular approach to complex problems in enterprise application development. In a typical object-oriented development approach you might implement logging functionality by putting logger statements in all your methods and Java classes. In an AOP approach you would instead modularize the logging services and apply them declaratively to the components that required logging. The advantage, of course, is that the Java class doesn't need to know about the existence of the logging service or concern itself with any related code. As a result, application code written using Spring AOP is loosely coupled. The best tool to utilize AOP to its capability is AspectJ. However AspectJ works at the byte code level and you need to use AspectJ compiler to get the aop features built into your compiled code. Nevertheless AOP functionality is fully integrated into the Spring context for transaction management, logging, and various other features. In general any AOP framework control aspects in three possible ways:

Joinpoints: Points in a program's execution. For example, joinpoints could define calls to specific methods in a class
Pointcuts: Program constructs to designate joinpoints and collect specific context at those points
Advices: Code that runs upon meeting certain conditions. For example, an advice could log a message before executing a joinpoint
What is spring? What are the various parts of spring framework? What are the different persistence frameworks which could be used with spring? 
Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development. The Spring modules are built on top of the core container, which defines how beans are created, configured, and managed. Each of the modules (or components) that comprise the Spring framework can stand on its own or be implemented jointly with one or more of the others. The functionality of each component is as follows:

The core container: The core container provides the essential functionality of the Spring framework. A primary component of the core container is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application’s configuration and dependency specification from the actual application code.

Spring context: The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality.

Spring AOP: The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components.

Spring DAO: The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code you need to write, such as opening and closing connections. Spring DAO’s JDBC-oriented exceptions comply to its generic DAO exception hierarchy.

Spring ORM: The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these comply to Spring’s generic transaction and DAO exception hierarchies.

Spring Web module: The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects.

Spring MVC framework: The Model-View-Controller (MVC) framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles, iText, and POI.
Explain the role of ApplicationContext in spring. 
While Bean Factory is used for simple applications; the Application Context is spring's more advanced container. Like 'BeanFactory' it can be used to load bean definitions, wire beans together and dispense beans upon request. It also provide

1) A means for resolving text messages, including support for internationalization.
2) A generic way to load file resources.
3) Events to beans that are registered as listeners.

Because of additional functionality, 'Application Context' is preferred over a BeanFactory. Only when the resource is scarce like mobile devices, 'BeanFactory' is used. The three commonly used implementation of 'Application Context' are

1. ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application's classpath by using the code

ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");

2. FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code

ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");

3. XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.
How does Spring supports DAO in hibernate? 
Spring’s HibernateDaoSupport class is a convenient super class for Hibernate DAOs. It has handy methods you can call to get a Hibernate Session, or a SessionFactory. The most convenient method is getHibernateTemplate(), which returns a HibernateTemplate. This template wraps Hibernate checked exceptions with runtime exceptions, allowing your DAO interfaces to be Hibernate exception-free.

public class UserDAOHibernate extends HibernateDaoSupport {

public User getUser(Long id) {
return (User) getHibernateTemplate().get(User.class, id);
public void saveUser(User user) {
if (log.isDebugEnabled()) {
log.debug(“userId set to: “ + user.getID());
public void removeUser(Long id) {
Object user = getHibernateTemplate().load(User.class, id);

What are the id generator classes in hibernate? 
increment: It generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. It should not the used in the clustered environment.
identity: It supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.
sequence: The sequence generator uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int
hilo: The hilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database. Do not use this generator with connections enlisted with JTA or with a user-supplied connection.
seqhilo: The seqhilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence.
uuid: The uuid generator uses a 128-bit UUID algorithm to generate identifiers of type string, unique within a network (the IP address is used). The UUID is encoded as a string of hexadecimal digits of length 32.
guid: It uses a database-generated GUID string on MS SQL Server and MySQL.
native: It picks identity, sequence or hilo depending upon the capabilities of the underlying database.
assigned: lets the application to assign an identifier to the object before save() is called. This is the default strategy if no element is specified.
select: retrieves a primary key assigned by a database trigger by selecting the row by some unique key and retrieving the primary key value.
foreign: uses the identifier of another associated object. Usually used in conjunction with a primary key association.
How is a typical spring implementation look like? 
For a typical Spring Application we need the following files

1. An interface that defines the functions.
2. An Implementation that contains properties, its setter and getter methods, functions etc.,
3. A XML file called Spring configuration file.
4. Client program that uses the function.
How do you define hibernate mapping file in spring? 
Add the hibernate mapping file entry in mapping resource inside Spring’s applicationContext.xml file in the web/WEB-INF directory.

< property name="mappingResources" >
< list >
< value > org/appfuse/model/User.hbm.xml < / value >
< / list >
< / property >
How do you configure spring in a web application? 
At the very least, you can simply add Spring’s ContextLoaderListener to your web.xml file:

< listener >
< listener-class > org.springframework.web.context.ContextLoaderListener < / listener-class >
< / listener >
Can you have xyz.xml file instead of applicationcontext.xml? 
ContextLoaderListener is a ServletContextListener that initializes when your webapp starts up. By default, it looks for Spring’s configuration file at WEB-INF/applicationContext.xml. You can change this default value by specifying a element named “contextConfigLocation.” Example:

< listener >
< listener-class > org.springframework.web.context.ContextLoaderListener

< context-param >
< param-name > contextConfigLocation < / param-name >
< param-value > /WEB-INF/xyz.xml< / param-value >
< / context-param >

< / listener-class >
< / listener >
How do you configure your database driver in spring?
Using datasource "org.springframework.jdbc.datasource.DriverManagerDataSource". Example:

< bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
< property name="driverClassName" >
< value > org.hsqldb.jdbcDriver < / value >
< / property >
< property name="url" >
< value > jdbc:hsqldb:db/appfuse < / value >
< / property >
< property name="username" > < value > sa < / value > < / property >
< property name="password" > < value > < / value > < / property >
< / bean >
How can you configure JNDI instead of datasource in spring applicationcontext.xml? 
Using "org.springframework.jndi.JndiObjectFactoryBean". Example:

< bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean" >
< property name="jndiName" >
< value > java:comp/env/jdbc/appfuse < / value >
< / property >
< / bean >
What are the key benefits of Hibernate? 
These are the key benifits of Hibernate:
Transparent persistence based on POJOs without byte code processing
Powerful object-oriented hibernate query language
Descriptive O/R Mapping through mapping file.
Automatic primary key generation
Hibernate cache: Session Level, Query and Second level cache.
Performance: Lazy initialization, Outer join fetching, Batch fetching
What is hibernate session and session factory? How do you configure sessionfactory in spring configuration file? 
Hibernate Session is the main runtime interface between a Java application and Hibernate. SessionFactory allows applications to create hibernate session by reading hibernate configurations file hibernate.cfg.xml.

// Initialize the Hibernate environment
Configuration cfg = new Configuration().configure();
// Create the session factory
SessionFactory factory = cfg.buildSessionFactory();
// Obtain the new session object
Session session = factory.openSession();

The call to Configuration().configure() loads the hibernate.cfg.xml configuration file and initializes the Hibernate environment. Once the configuration is initialized, you can make any additional modifications you desire programmatically. However, you must make these modifications prior to creating the SessionFactory instance. An instance of SessionFactory is typically created once and used to create all sessions related to a given context.
The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes. Instances may exist in one of three states:

transient: never persistent, not associated with any Session
persistent: associated with a unique Session
detached: previously persistent, not associated with any Session

A Hibernate Session object represents a single unit-of-work for a given data store and is opened by a SessionFactory instance. You must close Sessions when all work for a transaction is completed. The following illustrates a typical Hibernate session:
Session session = null;
UserInfo user = null;
Transaction tx = null;
try {
session = factory.openSession();
tx = session.beginTransaction();
user = (UserInfo)session.load(UserInfo.class, id);
} catch(Exception e) {
if (tx != null) {
try {
} catch (HibernateException e1) {
throw new DAOException(e1.toString()); }
} throw new DAOException(e.toString());
} finally {
if (session != null) {
try {
} catch (HibernateException e) { }
What is the difference between hibernate get and load methods? 
The load() method is older; get() was added to Hibernate’s API due to user request. The difference is trivial:
The following Hibernate code snippet retrieves a User object from the database:
User user = (User) session.get(User.class, userID);

The get() method is special because the identifier uniquely identifies a single instance of a class. Hence it’s common for applications to use the identifier as a convenient handle to a persistent object. Retrieval by identifier can use the cache when retrieving an object, avoiding a database hit if the object is already cached.
Hibernate also provides a load() method:
User user = (User) session.load(User.class, userID);

If load() can’t find the object in the cache or database, an exception is thrown. The load() method never returns null. The get() method returns
null if the object can’t be found. The load() method may return a proxy instead of a real persistent instance. A proxy is a placeholder instance of a runtime-generated subclass (through cglib or Javassist) of a mapped persistent class, it can initialize itself if any method is called that is not the mapped database identifier getter-method. On the other hand, get() never returns a proxy. Choosing between get() and load() is easy: If you’re certain the persistent object exists, and nonexistence would be considered exceptional, load() is a good option. If you aren’t certain there is a persistent instance with the given identifier, use get() and test the return value to see if it’s null. Using load() has a further implication: The application may retrieve a valid reference (a proxy) to a persistent instance without hitting the database to retrieve its persistent state. So load() might not throw an exception when it doesn’t find the persistent object in the cache or database; the exception would be thrown later, when the proxy is accessed.
What type of transaction management is supported in hibernate? 
Hibernate communicates with the database via a JDBC Connection; hence it must support both managed and non-managed transactions.

Non-managed in web containers:

< bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager" >
< property name="sessionFactory" >
< ref local="sessionFactory" / >
< / property >
< / bean >

Managed in application server using JTA:

< bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager." >
< property name="sessionFactory" >
< ref local="sessionFactory" / >
< / property >
< / bean >
What is lazy loading and how do you achieve that in hibernate? 
Lazy setting decides whether to load child objects while loading the Parent Object. You need to specify parent class.Lazy = true in hibernate mapping file. By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent. In this case hibernate issues a fresh database call to load the child when getChild() is actually called on the Parent object. But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database. Examples: Address child of User class can be made lazy if it is not required frequently. But you may need to load the Author object for Book parent whenever you deal with the book for online bookshop.

Hibernate does not support lazy initialization for detached objects. Access to a lazy association outside of the context of an open Hibernate session will result in an exception.
What are the different fetching strategies in Hibernate? 
Hibernate3 defines the following fetching strategies:

Join fetching - Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN.

Select fetching - a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.

Subselect fetching - a second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.

Batch fetching - an optimization strategy for select fetching - Hibernate retrieves a batch of entity instances or collections in a single SELECT, by specifying a list of primary keys or foreign keys.
What are different types of cache hibernate supports? 
Caching is widely used for optimizing database applications. Hibernate uses two different caches for objects: first-level cache and second-level cache. First-level cache is associated with the Session object, while second-level cache is associated with the Session Factory object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications. To reduce database traffic, second-level cache keeps loaded objects at the Session Factory level between transactions. These objects are available to the whole application, not just to the user running the query. This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided. In addition, you can use a query-level cache if you need to cache actual query results, rather than just persistent objects. The query cache should always be used in conjunction with the second-level cache. Hibernate supports the following open-source cache implementations out-of-the-box:

EHCache is a fast, lightweight, and easy-to-use in-process cache. It supports read-only and read/write caching, and memory and disk-based caching. However, it does not support clustering.
OSCache is another open-source caching solution. It is part of a larger package, which also provides caching functionalities for JSP pages or arbitrary objects. It is a powerful and flexible package, which, like EHCache, supports read-only and read/write caching, and memory- and disk-based caching. It also provides basic support for clustering via either JavaGroups or JMS.
SwarmCache is a simple cluster-based caching solution based on JavaGroups. It supports read-only or nonstrict read/write caching (the next section explains this term). This type of cache is appropriate for applications that typically have many more read operations than write operations.
JBoss TreeCache is a powerful replicated (synchronous or asynchronous) and transactional cache. Use this solution if you really need a true transaction-capable caching architecture.
Commercial Tangosol Coherence cache.
What are the different caching strategies? 
The following four caching strategies are available:
Read-only: This strategy is useful for data that is read frequently but never updated. This is by far the simplest and best-performing cache strategy.
Read/write: Read/write caches may be appropriate if your data needs to be updated. They carry more overhead than read-only caches. In non-JTA environments, each transaction should be completed when Session.close() or Session.disconnect() is called.
Nonstrict read/write: This strategy does not guarantee that two transactions won't simultaneously modify the same data. Therefore, it may be most appropriate for data that is read often but only occasionally modified.
Transactional: This is a fully transactional cache that may be used only in a JTA environment.
How do you configure 2nd level cache in hibernate?
To activate second-level caching, you need to define the hibernate.cache.provider_class property in the hibernate.cfg.xml file as follows:
< hibernate-configuration >
< session-factory >
< property name="hibernate.cache.provider_class" >org.hibernate.cache.EHCacheProvider< / property >
< / session-factory >
< / hibernate-configuration >

By default, the second-level cache is activated and uses the EHCache provider.
To use the query cache you must first enable it by setting the property hibernate.cache.use_query_cache to true in
What is the difference between sorted and ordered collection in hibernate? 
A sorted collection is sorted in-memory using java comparator, while order collection is ordered at the database level using order by clause.
What are the types of inheritance models and describe how they work like vertical inheritance and horizontal? 
There are three types of inheritance mapping in hibernate:

Example: Let us take the simple example of 3 java classes. Class Manager and Worker are inherited from Employee Abstract class.
1. Table per concrete class with unions: In this case there will be 2 tables. Tables: Manager, Worker [all common attributes will be duplicated]
2. Table per class hierarchy: Single Table can be mapped to a class hierarchy. There will be only one table in database called 'Employee' that will represent all the attributes required for all 3 classes. But it needs some discriminating column to differentiate between Manager and worker;
3. Table per subclass: In this case there will be 3 tables represent Employee, Manager and Worker

Differentiate between BeanFactory and ApplicationContext in spring.

- With ApplicationContext more than one config files are possible while only one config file or .xml file is possible with BeanFactory.
- ApplicationContext publishes events to beans that are registered as listeners while BeanFactory doesn't support this
- ApplicationContext support internationalization messages, application life-cycle events, validation and many enterprise services like JNDI access, EJB integration, remoting etc. while BeanFactory doesn't support any of these.

What is the difference between singleton and prototype bean?


Mainly it is the scope of a beans which defines their existence on the application
- Singleton: It means single bean definition to a single object instance per Spring IOC container.
- Prototype: It means a single bean definition to any number of object instances.


How do beans become 'singleton' or prototype?


- There exists an attribute in bean tag, called 'singleton’.
- If it is marked 'true', the bean becomes singleton.
- If it is marked 'false', the bean becomes prototype.

What type of transaction Management Spring support?


Spring supports two types of transaction management:

1. Programmatic transaction management
2. Declarative transaction management.

When do you use programmatic and declarative transaction management ?


- Programmatic transaction management is used preferably when you have a small number of transactional operations.
- Incase of large number of transactional operations it is better to use declarative transaction management.

What is IOC?


- IOC stands for Inversion of Control pattern.
- It is also called as dependency injection.
- This concept says that you do not create your objects but describe how they should be created.
- Similarly, you do not directly connect your components and services together in code but describe which services are needed by which components in a configuration file.
- A container then hooks them all up.

What are the different types of IoC (dependency injection) ?


There are three types of dependency injection:

a.) Constructor Injection : Here dependencies are provided as constructor parameters.
b.) Setter Injection : Dependencies are assigned through JavaBeans properties.
c.) Interface Injection : Injection is performed through an interface.

Spring supports only first two categories of Injection.

What are the benefits of IOC?


The main benefits of IOC or dependency injection are:

a.) It minimizes the amount of code in your application.
b.) It makes your application easy to test as it doesn't require any singletons or JNDI lookup mechanisms in your unit test cases.
c.) Loose coupling is promoted with minimal effort and least intrusive mechanism.
d.) IOC containers support eager instantiation and lazy loading of services.

What is Bean Wiring ?


Bean wiring means creating associations between application components i.e. beans within the spring container.

How do you access Hibernate using Spring ?


There are two ways to Spring’s Hibernate integration:
a.) By Inversion of Control with a HibernateTemplate and Callback
b.) By extending HibernateDaoSupport and Applying an AOP Interceptor

How would you integrate Spring and Hibernate using HibernateDaoSupport?


This can be done through Spring’s SessionFactory called LocalSessionFactory. The steps in integration process are:

a.) Configure the Hibernate SessionFactory
b.) Extend your DAO Implementation from HibernateDaoSupport
c.) Wire in Transaction Support with AOP

What are the various transaction manager implementations in Spring ?


1. DataSourceTransactionManager : PlatformTransactionManager implementation for single JDBC data sources.

2. HibernateTransactionManager: PlatformTransactionManager implementation for single Hibernate session factories.

3. JdoTransactionManager : PlatformTransactionManager implementation for single JDO persistence manager factories.

4. JtaTransactionManager : PlatformTransactionManager implementation for JTA, i.e. J2EE container transactions. 

What is Spring?


Spring is a framework that resolves common problems in JEE architecture. Managing business objects and encouraging practices such as programming interfaces rather than classes is a consistent way of using Spring. Spring addresses all architectural tiers with basic building block by utilizing IoC. Unique data access abstraction including abstraction of JDBC framework improves the productivity and reduces the errors using Spring. A flexible and powerful MVC framework which is integrated into the overall IoC container. 

Spring is an opensource lightweight looslycoupled aspect oriented and dependency injection(inversion of control) based java-jee framework to develop all kinds of java, jee applications.

What are the Core container module and Application context module?


Core Container Module: This module is the fundamental module of spring framework. For a spring-based application, BeanFactory is the core. The Spring framework was developed on top of this module. Spring container is made by this module.
Application Context Module: Spring is called a framework because of this module. The concept of BeanFactory is used to extend this module to provide support for internationalization (I18N) messages etc. Enterprise services such as JNDI,EJB integration, remoting and scheduling are supplied by this module. 

Explain Bean lifecycle in Spring framework.


1. The spring container finds the bean’s definition from the XML file and instantiates the bean.
2. Using the dependency injection, spring populates all of the properties as specified in the bean definition.
3. If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.
4. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
5. If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called.
6. If an init-method is specified for the bean, it will be called.
7. Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.

What is bean wiring?


Combining together beans within the Spring container is known as bean wiring or wiring. When wiring beans, you should tell the container what beans are needed and how the container should use dependency injection to tie them together.

Explain how to add a bean in spring application.



In the bean tag the id attribute specifies the bean name and the class attribute specifies the fully qualified class name.

What are singleton beans and how can you create prototype beans?


Beans defined in spring framework are singleton beans. There is an attribute in bean tag named ‘singleton’ if specified true then bean becomes singleton and if set to false then the bean becomes a prototype bean. By default it is set to true. So, all the beans in spring framework are by default singleton beans.

What are Inner Beans?


When wiring beans, if a bean element is embedded to a property tag directly, then that bean is said to the Inner Bean. The drawback of this bean is that it cannot be reused anywhere else.

What is Auto wiring? What are different types of Autowire types?


It is possible to automatic resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory.
You can wire the beans as you wish. But spring framework also does this work for you. It can auto wire the related beans together. All you have to do is just set the autowire attribute of bean tag to an autowire type.

There are four different types by which auto wiring can be done.
  • byName
  • byType
  • constructor
  • autodetect

What is meant by Weaving? What are the different points where weaving can be applied?


In Spring AOP makes it possible to modularize and separate logging, transaction like services and apply them declaratively to the components Hence programmer can focus on specific concerns. Aspects are wired into objects in the spring XML file in the way as JavaBean. This process is known as 'Weaving'.
The process of applying aspects to a target object to create a new proxy object is called as Weaving. The aspects are woven into the target object at the specified joinpoints.
  • Compile Time
  • Classload Time
  • Runtime

Explain the different types of AutoProxying.


BeanNameAutoProxyCreator: This proxy is used to identify beans to proxy through a list of names. It checks the matches that are direct, “xxx” and “*xxx”.
DefaultAdvisorAutoProxyCreator: This proxy is the implementation of BeanPostProcessor which creates AOP proxies. These AOP proxies are based on BeanFactory’s all Candidate Advisors. It is a generic class which does not have a specific code to handle any specific aspects.
Metadata autoproxying: The metadata autoproxy is concerned with the possibility to employ annotations in certain classes, like defining transactions. To configure this type of proxies, the source level metadata interpretation and the bean usage that employs those attributes is done by DefaultAdvisorAutoProxyCreator. 

What is DataAccessException?


DataAccessException is an unchecked RuntimeException. These type of exceptions are unforced by users to handle. This exception is used to handle the errors occurring when the details of the database access API in use, such as JDBC. 

Explain about PreparedStatementCreator.


PreparedStatementCreator is one of the most common used interfaces for writing data to database. The interface has one method createPreparedStatement().
PreparedStatement createPreparedStatement(Connection conn) throws SQLException;
When this interface is implemented, we should create and return a PreparedStatement from the Connection argument, and the exception handling is automatically taken care off.
When this interface is implemented, another interface SqlProvider is also implemented which has a method called getSql() which is used to provide sql strings to JdbcTemplate.

Explain about BatchPreparedStatementSetter.


If the user what to update more than one row at a shot then he can go for BatchPreparedStatementSetter. This interface provides two methods
setValues(PreparedStatement ps, int i) throws SQLException;
int getBatchSize();
The getBatchSize() tells the JdbcTemplate class how many statements to create. And this also determines how many times setValues() will be called.

Explain about RowCallbackHandler and why it is used.


n order to navigate through the records we generally go for ResultSet. But spring provides an interface that handles this entire burden and leaves the user to decide what to do with each row. The interface provided by spring is RowCallbackHandler. There is a method processRow() which needs to be implemented so that it is applicable for each and everyrow.
void processRow(java.sql.ResultSet rs);

What are the functionalities provided by the context package to enhance the BeanFactory functionality?


The functionalities provided by context package are as follows:
1. message access in i18n-style, through the MessageSource interface.
2. Resources access such as URLs and files, through which, the ResourceLoader interface, can be accessed and used.
3. Publication of events, through the beans that allow, implementing the ApplicationListener interface. It is done through the use, of the ApplicationEventPublisher interface.
4. Multiple loading contexts, allowing each to be focused on one particular layer, such as the web layer of an application, through the HierarchicalBeanFactory interface.

How can you achieve Internationalization using MessageSource?


Internationnalization using message source can be achieved by the following:
1>String get Mesage(String code, Objct[] args, String default, Local
loc): The basic method used for retrieving a message from the MessageSource. When no message is to be
found for the specified locale, the default message is used.
2> String getMessage(String code, Objct[] args, Locale loc): Essentially the
same as the last method, but with a difference: no default message is specified; if the
message cannot be found, a NoSuchMessageException is shown.
3> String getMessage(MessageSourceResolvable resolvable, Local locale):
properties used for the preceding methods are also wrapped in a class named
MessageSourceResolvable, which you can use with this method.


Enlist and explain the main methods associated with the Resource interface.


Methods associated with resource interface are as follows:
1> getInputStream(): it locates and opens the resource, returning an InputStream to read from
the resource.
2> exists(): returns a boolean which indicates whether this resource actually exists in physical form.
3> isOpen(): returns a boolean which indicates whether this resource represents a handle with an open
4> getDescription(): returns a description for this resource, which is used for error output when
working with the resource.


Give some examples where property editing is used in spring.


Following are examples for property editing in spring
1> setting of properties on beans is done by using PropertyEditors. To mention
java.lang.string as the value for a property of some bean you're declaring in XML file, Spring will use the ClassEditor to try resolving the parameter to a Class object.
2> passing HTTP request parameters in Spring's MVC framework can be done using all kinds of PropertyEditors that can be manually bind in all subclasses of the CommandController.


Explain the main AOP concepts and terminology


The main AOP concepts are as follows:
1> Aspect: a modularization of a concern that cuts through multiple classes.
2> Join point: is a point during which the execution of a programming, such as the execution of method or handling of an exception.
3> Advice: action taken by an aspect for a particular join point.
4> Point cut: a predicate that is matched to join points.
5> Introduction: declaration of additional methods or fields on behalf of a type.
6> Target object: object which is advised by one or more aspects.
7> AOP proxy: an object which is created by AOP framework for implementing the aspect contracts.
8> Weaving: linking of aspects with other application types or objects to create an advised object.


How can you use spring to resolve collaborators for your bean? Also state the advantages of auto wiring?


The spring can be used to resolve collaborators automatically by inspecting contents of the
The Autowiring has the following advantages in spring:
1. Reduces requirement for specifying properties or construction arguments.
2. Updates configuration while evolving of objects.
To understand this lets consider an example: modifying would not be required in configuration of a dependency while adding it to a class.
3. Switching to explicit wiring when code base is stable can be neglected.


List the limitations of auto wiring.


Autowiring has the following limitations:
1. Overriding and auto wiring are caused due to dependency in property and constructor argument setting.
2. Less precise as compared to explicit wiring.
3. Tools that generate documentation using a spring might not have access to wiring information.
4. There is a possibility of clash between bean definitions and argument or method to be wired.
The problem does not occur much in case of maps, arrays and collection and cannot be resolved randomly for dependencies which expect one value.


In scenarios where you have to avoid using auto wiring, what are the other options that can be explored to achieve the same.


In scenarios where using autowiring is prohibited, the following replacements can achive the same:
1. Abandon autowiring for favor of explicit wiring.
2. Avoid autowiring for a bean definition by setting the autowire-candidate for attributes to false as described in the next section.
3. Set a single bean definition as the primary candidate by setting the primary attribute of its
element to true.
4. When Java 5 or later is used, implementation needs more fine-grained control available with
annotation-based configuration.


How do you call the multiple lifecycle mechanisms configured for the same bean?


Multiple lifecycle mechanisms which are configured for the same bean, with different initialization methods, are called by the following ways :
1. Methods annotated with use of @PostConstruct
2. afterPropertiesSet() as stated by the InitializingBean callback interface
3. Custom configuration init() method
Destroy methods are called in the same order as follows :
1. Methods annotated with use of @PreDestroy
2. destroy() as stated by the DisposableBean callback interface
3. destroy() method with custom configuration

What are the methods associated with the FactoryBean interface?


Following are the methods associated with factory bean interface:
1> Object getObject(): this returns an instance of the object which the factory creates. This instance can
possibly be shared, depending on the factory returns singletons or prototypes.
2> boolean isSingleton(): this returns true if this FactoryBean returns singletons, false
3> Class getObjectType(): this returns the object type returned by the getObject() method or
null if the type is unknown in advance.

What are the annotations supported by the spring framework?


Due to addition of some core features from the JavaConfig project to the Spring Framework,the following annotations are now directly supported:
• @Configuration
• @Bean
• @DependsOn
• @Primary
• @Lazy
• @Import
• @ImportResource
• @Value


Explain in brief the metadata contained in the BeanDefinition objects


Bean definitions contain the following metadata:
1. A package-qualified class name: which is the actual implementation class of the bean being defined.
2. Bean behavioral configuration elements, which state the procedure for how the bean should behave in the container
3. References to other beans that are required for the bean to do its work; these references are also called collaborators or dependencies.
4. Other configuration settings to set when a new object is created, for example, the number of connections to use in a bean that manages a connection pool or the size limit of the pool.


What are the different properties the metadata translates into to make up the bean definition?


Metadata translates into the following properties to make up
1. Property defined in class the section called “Instantiating beans”
2. Property defined in name the section called “Naming beans” scope constructor arguments the section known as “Dependency injection”
3. Properties the section known as “Dependency injection” auto wiring mode the section known as “Autowiring collaborators”
4. lazy-initialization mode the section called “Lazy-initialized beans”
5. Initialization method the section called “Initialization callbacks”
6. Destruction method the section called “Destruction callbacks”


Briefly describe the 2 ways in which the class property can be used.


The class property can be put to use in the following ways:
1. It is used to specify the java bean for class to be constructed when container directly creates java bean by calling constructor reflectively. This procedure is also used for java code which uses a new operator.
2. It is also used to specify the class which contains static factory method which is invoked for creating object. Another case in this which doesn’t occur much is when static factory method is invoked by container on a class for creating the bean.


Explain the dependency resolution process


The dependency resolution process is carried out as follows:
1. Creation an initialization of application text inside configuration metadata( can be specified in XML, java code,annotations) is done. This describes all the beans.
2. For each bean, its dependency is expressed in the form of properties, constructor arguments, or
arguments to the static-factory method if that is used instead of a normal constructor.
3. Each property or constructor argument is actual definition of the value which belong to set, or a reference to another bean which is in the container.
4. Each property or constructor argument which is a value is gone through conversion from its specified format to the actual type of that property or constructor argument.


Give examples of how spring platform can be used by an application developer.


The spring platform can be used by an application developer in the following way ::
• Java method can be made to execute in a database transaction without having to deal with transaction APIs.
• Local Java method can be made a remote procedure without having to deal with remote APIs.
• Local Java method can be made a management operation without having to deal with JMX APIs.
• Local Java method can be made a message handler without having to deal with JMS APIs.


What are the various ways of using spring?


There are various ways and forms in which springs can be used.
They are listed as follows:
1. Full-fledged Spring web app
2. Spring middle-tier provides help of a third-party web framework
3. Remote usage scenario: allow the system to be used to remotely use the resources from the server. The remote usage can be done to grab the data from the server or for troubleshooting the environment.
4. EJB -- Wrapping existing POJOs


Specify the locations where spring can publish its artifacts.


Spring generally publishes its artifacts to four different places:
1. Community download site
2. Maven Central, which is considered the default repository that Maven queries, and does not require any special configuration to use.
3. The Enterprise Bundle Repository (EBR), which is considered to be run by SpringSource and also hosts all the libraries that integrate with Spring.
4. Public Maven repository hosted on Amazon S3 for the development of snapshots and milestone releases. The jar file names are given in the same form as Maven Central, which makes it a useful place to get development versions of Spring to use with other libraries Spring Framework deployed in Maven Central.


What are the features of the new spring build system in use now days?


Now the new Spring build system is used which comes with the following features :
1. "Spring Built" system which is based on Ivy
2. consistent procedure for deployment
3. dependency management which is made consistent
4. consistent generation for OSGi


List in brief the new features Spring 3.0 has to offer


Spring 3.0 offers the following new features:
1. Spring Expression Language
2. IoC enhancements or Java based bean metadata
3. field formatting and General-purpose type conversion system
4. Object to XML mapping functionality (OXM) moved from Spring Web Services project
5. Comprehensive REST support
6. @MVC additions
7. Declarative model validation
8. Early support for Java EE 6
9. Embedded database support