Monday, October 4, 2010

Spring interview questions

1. What are the two types of IOC container in spring framework?
Spring provides two types of IoC container implementation. The basic one is called bean factory. The
more advanced one is called application context, which is a compatible extension to the bean factory.
The interfaces for the bean factory and the application context are BeanFactory and
ApplicationContext, respectively. The interface ApplicationContext is a subinterface of
BeanFactory for maintaining compatibility.
2. How to Instantiate the ApplicationContext?
     ApplicationContext is an interface only. We have to instantiate an implementation of it. There are 4 ways available to instantiate the ApplicationContext.
     The ClassPathXmlApplicationContext implementation builds an application context by loading an XML
configuration file from the classpath. We can also specify multiple configuration files for it.
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
     Besides ClassPathXmlApplicationContext, there are several other ApplicationContext
implementations provided by Spring. FileSystemXmlApplicationContext is used to load
XML configuration files from the file system, while XmlWebApplicationContext and
XmlPortletApplicationContext can be used in web and portal applications only.
3. How to get bean from application context?
     To get a declared bean from a bean factory or an application context, you just make a call to the
getBean() method and pass in the unique bean name. The return type of the getBean() method is
java.lang.Object, so you have to cast it to its actual type before using it.

4. What do you mean by autowiring?
        The Spring IoC container can wire beans automatically.We no need to inject other bean reference manually. We only have to specify the auto-wiring mode in the autowire attribute of tag.

5. What are all the different mode's of autowiring?
    There are 5 different modes are there.
    i)  no  - No auto-wiring will be performed. You must wire the dependencies explicitly. The default mode is no, but this can be changed by setting the default-autowire attribute of the root element. This default mode will be overridden by a bean’s own mode if specified.

   ii) byName - For each bean property, wire a bean with the same name as the property.

   iii) byType - For each bean property, wire a bean whose type is compatible with that of the property.
If more than one bean is found, an UnsatisfiedDependencyException will be thrown.

   iv) constructor - For each argument of each constructor, first find a bean whose type is compatible with
the argument’s. Then pick the constructor with the most matching arguments. In case of any ambiguity, an UnsatisfiedDependencyException will be thrown.
   v) autodetect - If a default constructor with no argument is found, the dependencies will be auto-wired
by type. Otherwise, they will be auto-wired by constructor.