Spring Interview Questions

Java Quick Notes

Refresh Your Java

We are Agile, believe in less Documentation - Only Quick notes of Java/J2ee Read more....

Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet

"Click on other Tabs for more Questions"  

"Spring "


1 )   What is dependency injection or Inverse of Control ?


Inversion of Control (IoC) is an object-oriented
programming practice where the object coupling is bound at run time by an assembler
object and is typically not known at compile time using static analysis.

These Objects can be obtained by means of Dependency lookup or Dependency injection.
Dependency lookup is a pattern where a caller asks the container object for an
object with a specific name or of a specific type.
Dependency injection is a
pattern where the container passes objects by name to other objects,
via either constructors, properties, or factory methods.

Back to top

2 )   How many ways you could achieve Dependency Injection in Spring ?


Dependency Injection could be accomplished in two ways either with constructor arguments
or with Setter Getter methods.

Setter-based dependency injection is realized by calling setters on your beans after invoking
a no-argument constructor or no-argument static factory method to instantiate your bean. Beans
defined in the BeanFactory that use setter-based dependency injection are true JavaBeans.

<bean id="exampleBean" class="examples.ExampleBean">
  <property name="beanOne"><ref bean="anotherExampleBean"/></property>

Constructor-based dependency injection is realized by invoking a constructor with a number of
arguments, each representing a collaborator or property.

<bean id="exampleBean" class="examples.ExampleBean">
  <constructor-arg><ref bean="anotherExampleBean"/></constructor-arg>

Back to top

3 )   What are the Different Modules of Spring ?


  • null
    Sample Img 3

 Inversion of Control container (dependency injection)
o  Aspect-oriented programming framework
o  Data access framework
o  Transaction management framework
o  Model-view-controller framework
o  Remote access framework
o   Batch framework
o  Integration framework


Back to top

4 )   What is Spring BeanFactory ?


The BeanFactory is the actual container which instantiates, configures, and manages a number
of beans
. These beans typically collaborate with one another, and thus have dependencies
between themselves.

You can get the Bean Factory as follows .
ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
        new String[] {"applicationContext.xml"});

BeanFactory factory = (BeanFactory) appContext;

Back to top

5 )   Spring Bean life cycle ?


  • Spring Bean life cycle
    Sample Img 5

Spring's bean has a very elaborated life cycle which gives opportunities to hook up some custom code or logic in various life cycle stages. There are two distinct spring containers one is bean factory and another is application context.  More precisely, only one additional phase is added in case of application context.

1. Instantiate: in this phase container finds the bean's definition and instantiates it.
2. Populate properties: in this phase using the dependency injection all the properties are populated which are specified in the bean definiton (in the xml file).
3. Set Bean Name : If BeanNameAware interface is implemented the factory calls the setBeanName() passing the Bean's Id.
4. Set Bean factory: if BeanFactoryAware interface is implemented setBeanFactory() method is called.
5. ApplicationContextAware: This step is valid only if the Application context container is used. In this phase if bean implements the ApplicationcontextAware then setApplicationContext() method is called.
6. Pre-initialization: If any BeanPostProcessors are associated with the bean then their postProcessBeforeInitialization() methods will be called.
7. InitializingBean: If an init-methodis specified for the bean then it is called.
8. Post Initialization: If there are any BeanPostProcessors are associated then postProcessAfterInitialization() is called.

9. Destroy: If bean implements the DisposableBean interface then destroy() method is called.

Back to top

6 )   How you create Singleton beans by using Spring ?


In Spring Beans are defined two modes: singleton or non-singleton.
When a bean is a singleton, only one shared instance of the bean will be managed and all
requests for beans with an id matching that bean definition will result in that one
pecific bean instance being returned.

Beans are deployed in singleton mode by default, unless you specify otherwise.

Please see below you could manage this feature with  'singleton' attribute, please see below.

<bean name="yetAnotherExample"
      class="examples.ExampleBeanTwo" singleton="true"/>

Back to top

7 )   How to create Prototype beans by using Spring ?


The non-singleton, prototype mode of a bean deployment results in the creation of
a new bean instance every time a request for that specific bean is done.
<bean id="exampleBean"
      class="examples.ExampleBean" singleton="false"/>

Back to top

8 )   What is AutoWire in Spring ? What are the other possible values ?


A BeanFactory is able to autowire relationships between collaborating beans. This means
it's possible to automatically let Spring resolve collaborators (other beans) for your
bean by inspecting the contents of the BeanFactory. The autowiring functionality has five modes.

No                  -  No autowiring at all. Bean references must be
                       defined via a ref element. This is the default.

byName              -  Autowiring by property name.
byType              -  Allows a property to be autowired if there
                       is exactly one bean of the property type in the BeanFactory.

Constructor        -  This is analogous to byType, but applies to constructor arguments.
Autodetect         -  Chooses constructor or byType through introspection of the bean class.

Back to top

9 )   How to get the Spring Context ?


ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
        new String[] {"applicationContext.xml"});
BeanFactory factory = (BeanFactory) appContext;

Back to top

10 )   PropertyPlaceholderConfigurer ?


The PropertyPlaceholderConfigurer, implemented as a bean factory post-processor, is used
to externalize some property values from a BeanFactory definition, into another separate
file in Java Properties format.

Create PropertyPlaceholderConfigurer  Programmatically :

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
  <property name="driverClassName" value="${jdbc.driverClassName}"/>
  <property name="url" value="${jdbc.url}"/>
  <property name="username" value="${jdbc.username}"/>
  <property name="password" value="${jdbc.password}"/>


XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans.xml"));
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
cfg.setLocation(new FileSystemResource("jdbc.properties"));

By Config :

 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
        <property name="ignoreUnresolvablePlaceholders" value="true"/>

By Using Util :
<util:properties id="messages" location="classpath:messages.properties"/>

By Using PropertySource :
@PropertySource(name = "someName", value = {"classpath:a.properties", "classpath:b.properties"})
public class MyConfiguration {

Back to top

11 )   How to read Message Sources using Spring Application Context ?


Here are the Steps to follow to use Internationalization by reading Message Resource.

1) Add this to your spring config XML .
      <bean id="messageSource" class="org.springframework.context.support.
            <property name="basename" value="messages"/>
    2) create a property file name calles "messages.properties" and place that in
    WEB-INF/Classes folder.

    3) Include the following JSTL in jsp.
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

Back to top

12 )   Where could you add your Spring Configuration for a Web App ?


 Add the following two entries to the Web.xml

Step 1:


Step 2:

Back to top

13 )   Can you have mulitiple implementations for same bean ?


 Yes, you can have this, you need to configure the Parent and Chield Beans as follows.

<bean id="inheritedTestBean" abstract="true"
  <property name="name" value="parent"/>
  <property name="age" value="1"/>

<bean id="inheritsWithDifferentClass"
      parent="inheritedTestBean" init-method="initialize">
  <property name="name" value="override"/>
  <!-- the age property value of 1 will be inherited from  parent -->



Back to top

14 )    ApplicationContextAware ?


A bean which implements this interface and is deployed into the context will be called back
on creation of the bean, using the interface's setApplicationContext() method, and provided
with a reference to the context, which may be stored for later interaction with the context.

public class DefaultBeanLoader implements  ApplicationContextAware {
        private ApplicationContext applicationContext;
                public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
                this.applicationContext = applicationContext;

Back to top

15 )   What is BeanWrapper ? How to use it ?


The BeanWrapper offers functionality to set and get property values (individually
or in bulk), get property descriptors, and to query properties to determine if they
are readable or writable.

Company c = new Company();
BeanWrapper bwComp = BeanWrapperImpl(c);

bwComp.setPropertyValue("name", "your Company");

Back to top

16 )   What is JdbcTemplate ? How to use this ?


This is the very important class in the JDBC core package, it simplifies the use of JDBC
since it handles the creation and release of resources. This helps to avoid common errors
like forgetting to always close the connection.

// create a JdbcTemplate and set data source
JdbcTemplate jt = new JdbcTemplate();

// create a custom translator and set the datasource for the default translation lookup
MySQLErrorCodesTransalator tr = new MySQLErrorCodesTransalator();
// use the JdbcTemplate for this SqlUpdate
SqlUpdate su = new SqlUpdate();

su.setSql("update orders set shipping_charge = shipping_charge * 1.05");

Back to top

17 )   How to set up "Hibernate SessionFactory setup in a Spring application context" ?


<bean id="mySessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
    <property name="dataSource" ref="myDataSource"/>
    <property name="mappingResources">
    <property name="hibernateProperties">
        <prop key="hibernate.dialect">net.sf.hibernate.dialect.MySQLDialect</prop>

Back to top

18 )   How many ways you can have Hibernate-Spring integration (Inversion of control for Hibernate) ?


Could be done in Two ways.
i)By using "HibernateTemplate"
ii) By using  "HibernateDaoSupport" .

With HibernateTemplate and Callback method:
public class YourDaoImpl implements YourDao {
    private SessionFactory sessionFactory;
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
   public Collection loadProductsByCategory(final String category) throws DataAccessException {
        HibernateTemplate ht = new HibernateTemplate(this.sessionFactory);
        return (Collection) ht.execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException {
                Query query = session.createQuery(
                    "from test.Product product where product.category=?");
                query.setString(0, category);
                return query.list();

By uisng HibernateDaoSupport :
public class YourDaoImpl extends HibernateDaoSupport implements YourDao {
   public Collection loadProductsByCategory(String category)
            throws DataAccessException, MyException {

        Session session = getSession(getSessionFactory(), false);
        try {
            List result = session.find(
                "from test.Product product where product.category=?",
                category, Hibernate.STRING);
            if (result == null) {
                throw new MyException("invalid search result");
            return result;
        }  catch (HibernateException ex) {
            throw convertHibernateAccessException(ex);

Similarly you also have the following
i)  "JdoTemplate and JdoDaoSupport"
ii) TopLinkTemplate and TopLinkDaoSupport
iii) n iBATIS API  SqlMapClientTemplate and SqlMapClientDaoSupport


Back to top

19 )   Spring MVC ?


Spring MVC frame work is another popular MVC framework for Web Apps like Struts.

Below is the sample Spring MVC configuration for the Log In Functionality.

Step 1 :

public class StartController extends SimpleFormController  {
 protected ModelAndView onSubmit(HttpServletRequest httpServletRequest, HttpServletResponse
 httpServletResponse, Object o, BindException e) throws Exception {
    StartForm form = (StartForm) o;

    if (form.getCommand().equals("startForm")) {
        return new ModelAndView(new RedirectView("newOrder/newOrder.htm"));

  protected Object formBackingObject(HttpServletRequest httpServletRequest) throws Exception {
    AddDocumentForm form = new AddDocumentForm();
    return form;

  protected Map referenceData(HttpServletRequest request, Object o, Errors errors) throws Exception {
    Map<String, Object> map = super.referenceData(request, o, errors);
    return map;

View :
   <bean name="/start.htm" class="com.salesorder.StartController">
        <property name="sessionForm" value="true"/>
        <property name="commandName" value="startForm"/>
        <property name="commandClass" value="com.salesorder.StartForm"/>
        <property name="formView" value="salesorder/start"/>
        <property name="successView" value="start.htm"/>

Resolver :

Views in Spring are addressed by a view name and are resolved by a view resolver,
Spring Offers Several View Resolvers such as "AbstractCachingViewResolver",

Each of the above solves different technical solution and offers different

"InternalResourceViewResolver" is most commonly used one , could be used as follows.

<bean id="viewResolver" class="
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
  <property name="prefix" value="/WEB-INF/jsp/"/>
  <property name="suffix" value=".jsp"/>

Back to top

20 )   Spring Integration with JSP-JSTL.


Just as with any other view technology you're integrating with Spring, for JSPs you'll
need a view resolver that will resolve your views. The most commonly used view resolvers
when developing with JSPs are the InternalResourceViewResolver and the
ResourceBundleViewResolver. Both are declared in the WebApplicationContext

<bean id="viewResolver" class="org.springframework.web.servlet.view.
  <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
  <property name="prefix" value="/WEB-INF/jsp/"/>
  <property name="suffix" value=".jsp"/>

Similarly there are some other resolovers .
i) org.springframework.web.servlet.view.velocity.VelocityViewResolver.
Ii) org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer

Back to top

21 )   Can you use Structs along with Spring ? Spring - Struts Intergration ?



 i) ContextLoaderPlugin
To configure this plug-in, add the following XML to the plug-ins section near the bottom of your struts-config.xml file:

The location of the context configuration files can be customized using the "contextConfigLocation" property.
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
  <set-property property="contextConfigLocation"


ii) <controller>
  <set-property property="processorClass"

iii) ActionSupport Classes

public class YourAction extends DispatchActionSupport {

    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response)
            throws Exception {
        WebApplicationContext ctx = getWebApplicationContext();
        UserManager mgr = (UserManager) ctx.getBean("userManager");
        return mapping.findForward("success");

Back to top

22 )   How to create PDF with Spring ?



<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

    <bean name="*.pdf" class="common.PDFView">



import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;
import org.springframework.web.servlet.view.document.AbstractPdfView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.util.Map;

public class PDFView extends AbstractPdfView {
  private String filename;

  public String getFilename() {
    return filename;

  public void setFilename(String filename) {
    this.filename = filename;

  protected void buildPdfDocument(
          Map model,
          Document doc,
          PdfWriter writer,
          HttpServletRequest req,
          HttpServletResponse resp)
          throws Exception {

    PdfContentByte cb = writer.getDirectContent();
    PdfReader reader = new PdfReader(new FileInputStream(filename));
    for (int i = 1; i <= reader.getNumberOfPages(); i++) {
      PdfImportedPage page = writer.getImportedPage(reader, i);
      cb.addTemplate(page, 0, 0);

  protected Document newDocument() {
    return new Document();




Back to top

23 )   How to use Spring in a Servlet Based Web Application ?


Java Code:

ApplicationContext beanFactory =

Web.xml changes



Back to top

24 )    How to use JMS with Spring (JmsTemplate)


public class JmsQueueSender {
  private JmsTemplate jmsTemplate;
  private Queue queue;
  public void setConnectionFactory(ConnectionFactory cf) {
    jt = new JmsTemplate102(cf, false);
  public void setQueue(Queue q) {
    queue = q;
  public void simpleSend() {
    this.jmsTemplate.send(this.queue, new MessageCreator() {
      public Message createMessage(Session session) throws JMSException {
        return session.createTextMessage("hello queue world");

Back to top

25 )   How many way Spring Support Remote functionality ?


Spring support Remoting several ways, but the following are important ones among them.

Remote Method Invocation (RMI). Through the use of the RmiProxyFactoryBean and the
RmiServiceExporter Spring supports both traditional RMI (with java.rmi.Remote interfaces
and java.rmi.RemoteException) and transparent remoting via RMI invokers.

Spring's HTTP invoker. Spring provides a special remoting strategy which allows for Java
serialization via HTTP, supporting any Java interface (just like the RMI invoker). The
corresponding support classes are HttpInvokerProxyFactoryBean and HttpInvokerServiceExporter.
JAX RPC. Spring provides remoting support for Web Services via JAX-RPC.

<bean id="accountService" class="example.AccountServiceImpl">
    <!-- any additional properties, maybe a DAO? -->
Next we'll have to expose our service using the RmiServiceExporter:
<bean class="org.springframework.remoting.rmi.RmiServiceExporter">
        <!-- does not necessarily have to be the same name as the bean to be exported -->
        <property name="serviceName" value="AccountService"/>
        <property name="service" ref="accountService"/>
        <property name="serviceInterface" value="example.AccountService"/>
        <!-- defaults to 1099 -->
        <property name="registryPort" value="1199"/>

HTTPInvoker :
Server side :
<bean id="httpInvokerProxy" class="org.sprfr.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
  <property name="serviceUrl" value="http://remotehost:8080/AccountService"/>
  <property name="serviceInterface" value="example.AccountService"/>

<property name="httpInvokerRequestExecutor"> <bean class="org.springframework.remoting.
httpinvoker.CommonsHttpInvokerRequestExecutor"/> </property>

Web Services:
Exposing services using JAX-RPC :
Spring has a convenience base class for JAX-RPC servlet endpoint implementations -
ServletEndpointSupport. To expose our AccountService we extend Spring's ServletEndpointSupport
class and implement our business logic here, usually delegating the call to the business layer

public class AccountServiceEndpoint extends ServletEndpointSupport
implements RemoteAccountService {
    private AccountService biz;

Accessing Web Services
<bean id="yourWebService" class="org.springframework.remoting.jaxrpc.JaxRpcPortProxyFactoryBean">
        <property name="serviceInterface">
        <property name="wsdlDocumentUrl">
        <property name="namespaceUri">
        <property name="serviceName">
        <property name="portName">

Back to top

26 )   Spring DWR example


 Step 1 : Create a Service "YourPageManager" with different methods

  Step 2: Add the following Spring Config.

<dwr:remote javascript="YourPageManagerJS">
   <dwr:include method="getAccountSalesList"/> 
   <dwr:include method="getEmailAddressByWebUserObjid"/> 
   <dwr:include method="getStates"/> 
   <dwr:include method="getTransportType"/>
   <dwr:include method="getContacts"/> 
   <dwr:include method="findContacts"/>
   <dwr:filter class="com.your.ajax.DwrSecurityFilter"/>

     <dwr:convert type="bean" class="com.yourApp.ContactDetails"
     javascript="Contact" />
 <bean id="Contact" class="com.yourApp.ContactDetails">

Step 3 :

Add the following to JSP

Jsp changes :
<script type="text/javascript" src="<%=request.getContextPath()%>/dwr/engine.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/dwr/util.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/dwr/interface/YourPageManagerJS.js"></script>


YourPageManagerJS.addContactsToDTO(contactInfo, function(data){    
    window.saveClicked = false; 
    window.contactSaved = true;

Back to top

27 )   How to declare DispatcherServlet in Web.xml


  • Spring DispatcherServlet set up
    Sample Img 27

The DispatcherServlet :
The DispatcherServlet is a central servlet that dispatches requests
to controllers, this plays the “Front Controller” role in Spring MVC. 





Back to top

29 )   Spring Command controllers Overview


There are several types of Command controllers exist in Spring MVC including
each of these Controller offers different type of implementation capabilties.

Among these most commonly used one is "SimpleFormController", following code
 illustrates how to use this Controller.

This Controller offering form submission. The Controller class lets you specify
 a command object, a viewname for the form, a viewname for page you want to show
 the user when form submission has succeeded, and more.

Most important methods you should override when you use this Controller class are
 i) formBackingObject(HttpServletRequest httpServletRequest) :
  A method which you can use to set the New Form to your View.
 ii) Map referenceData():
     A method which you can use to pass model data to your view in the form of a Map;
   onSubmit(HttpServletRequest httpServletRequest, HttpServletResponse
     httpServletResponse, Object o, BindException e) 
commandClass :
"commandClass" could be used to set your Form as following .
  <property name="commandClass" value="com.salesorder.StartForm"/>
commandName :
"commandName" with which you can  

Back to top

Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet

This Portal is intended to put all Java/J2ee related topics at one single place for quick referance, not only Technical , but also the Project Management Related thing such as Development Process methodoogies build process, unit testing etc.,

This Portal has More than 500 Java Interview Questions (also could be Considered as Quick Notes) very neatly separated topic by topic with simple diagrams which makes you easily understandable. Importantly these are from our Realtime expericance.

Face Book

Get a PDF

Face Book
Same look (Read) on any device, this is Ads free

Go To Site Map