Spring Interview Questions and Answers: Overview

Spring framework is very vast, widely used and often beginners get overwhelmed by it. If you are pressed for time, try to learn at least the core basics in this post and the first two links shown below. Learning the fundamentals described can save you a lot of frustrations, especially knowing the DI and IoC basics, bean life cycle and bean scopes.

Q. What do you understand by the terms Dependency Inversion Principle (DIP), Dependency Injection (DI) and Inversion of Control (IoC) container ?

A.
  • Dependency Inversion Principle (DIP) is a design principle which is in some ways related to the Dependency Injection (DI) pattern. The idea of DIP is that higher layers of your application should not directly depend on lower layers. Dependency Inversion Principle does not imply Dependency Injection. This principle doesn’t say anything about how higher la yers know what lower layer to use. This could be done as shown below by coding to interface using a factory pattern or through Dependency Injection by using an IoC container like Spring framework, Pico container, Guice, or Apache HiveMind.




        The Dependency Inversion Principle (DIP) states that

  • High level modules should not depend upon low level modules. Both should depend upon abstractions.
  • Abstractions should not depend upon details. Details should depend upon abstractions.
When this principle is applied, the higher level classes will not be working directly with the lower level classes, but with an abstract layer. This gives us the flexibility at the cost of increased effort.Here are some code snippets for DIP.

Firstly define the abstraction layer.

package principle_dip2;

public interface AnimalHandler {
    public abstract void handle( );
}


package principle_dip2;

public interface AnimalHelper {
    public abstract void help( );
}


Now the implementation that depends on the abstraction as opposed to the implementation.

package principle_dip2;

public class CircusService {
    
    AnimalHandler handler;
    
    public void setHandler(AnimalHandler handler) {
        this.handler = handler;
    }

    public void showStarts( ) {
        //code omitted for brevity
        handler.handle( );
    }
}



package principle_dip2;

public class TigerHandler implements AnimalHandler{
    
   AnimalHelper helper;
    
    public void setHelper(AnimalHelper helper) {
        this.helper = helper;
    }

    public void handle( ){
        //...
        helper.help( );
        //...
    }
}



package principle_dip2;

public class TigerHelper implements AnimalHelper{
    
    public void help( ){
        //......
    }
}

  • Dependency Injection (DI) is a pattern of injecting a class’s dependencies into it at runtime. This is achieved by defining the dependencies as interfaces, and then injecting in a concrete class implementing that interface to the constructor. This allows you to swap in different implementations without having to modify the main class. The Dependency Injection pattern also promotes high cohesion by promoting the  Single Responsibility Principle (SRP), since your dependencies are individual objects which perform discrete specialized tasks like data access (via DAOs) and business services (via Service and Delegate classes) .

  • The Inversion of Control Container (IoC) is a container that supports Dependency Injection. In this you use a central container  like Spring framework, Guice, or HiveMind, which defines what concrete classes should be used for what dependencies throughout your application. This brings in an added flexibility through looser coupling, and it makes it much easier to change what dependencies are used on the fly. The basic concept of the Inversion of Control pattern is that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up. Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.


The real power of DI and IoC is realized  in its ability to replace the compile time binding of the relationships between classes with  binding those relationships at runtime. For example, in Seam framework, you can have a real and mock implementation of an interface, and at runtime decide which one to use based on a property, presence of another file, or some precedence values. This is incredibly useful if you think you may need to modify the way your application behaves in different scenarios. Another real benefit of DI and IoC is that it makes your code easier to unit test. There are other benefits like promoting looser coupling without any proliferation of factory and singleton design patterns, follows a consistent approach for lesser experienced developers to follow, etc. These benefits can come in at the cost of the added complexity to your application and has to be carefully manged by using them only at the right places where the real benefits are realized, and not just using them because many others are using them.



Note: The CDI (Contexts and Dependency Injection)  is an attempt at describing a true standard on Dependency Injection. CDI is a part of the Java EE 6 stack, meaning an application running in a Java EE 6 compatible container can leverage CDI out-of-the-box. Weld is the reference implementation of CDI.


 Q. In your experience, why would you use Spring framework?
A.
  • Spring has a layered architecture with over 20 modules to choose from. This means, use what you need and leave what you don't need now. Spring simplifies JEE through POJO programming. There is no behind the scene magic in Spring as in JEE programming. POJO programming enables continuous integration and testability.

  • Spring framework's core functionality is dependency injection (DI). Dependency injection promotes easy unit testing and more maintainable and flexible code. DI code is much easier to test. The functionality expressed by the object can be tested in a black box by building 'mock' objects implementing the interfaces expected by your application logic. DI code is much easier to reuse as the 'depended' functionality is extrapolated into well defined interfaces, allowing separate objects whose configuration is handled by a suitable application platform to be plugged into other objects at will. DI code is more flexible. It is innately loosely coupled code to an extreme. This allows the programmer to pick and choose how objects are connected based exclusively on their required interfaces on one end and their expressed interfaces on the other.
  • Spring supports Aspect Oriented Programming (AOP), which enables cohesive development by separating application business logic from system services. Supporting functionalities like auditing, gathering performance and memory metrics, etc can be enabled through AOP.
  • Spring also provides a lot of templates which act as base classes to make using the JEE standard technologies a breeze to work with. For example, the JdbcTemplate works well with JDBC, the JpaTemplate does good things with JPA, JmsTemplate makes JMS pretty straightforward. The RestTemplate is simply awesome in it's simplicity. Simplicity means more readable and maintainable code.
  • When writing software these days, it is important to try and decouple as much middleware code from your business logic as possible. The best approach when using remoting is to use Spring Remoting which can then use any messaging or remoting technology under the covers. Apache Camel is a powerful open source integration framework based on known Enterprise Integration Patterns with powerful Bean Integration. Apache Camel is designed to work nicely with the Spring Framework in a number of ways.
  • It also provides declarative transactions, job scheduling, authentication, a fully-fledged MVC web framework, and integration to other frameworks like Hibernate, iBatis, JasperReports, JSF, Struts, Tapestry, Seam, Quartz job scheduler, etc.
  • Spring beans can be shared between different JVMs using Terracotta. This allows you to take existing beans and spread them across a cluster, turn Spring application context events into distributed events, export clustered beans via Spring JMX, and make your Spring applications highly available and clustered. Spring also integrate well with other clustering solutions like Oracle's Coherance.
  • Spring favors unchecked exceptions and eliminates unsightly try, catch, and finally (and some times try/catch within finally itself) blocks. The Spring templates like JpaTemplate takes care of closing or releasing a database connection. This prevents any potential resource leaks and promotes more readable code.
  • It prevents the proliferation of factory and singleton pattern classes that need to be created to promote loose coupling if not for using a DI framework like Spring or Guice.
Q. In your experience, what do you don't like about Spring? Are there any pitfalls?
A.
  • Spring has become very huge and bulky. So, don't over do it by using all its features because of the hype that Spring is good. Look at what parts of Spring really provides some benefits for your project and use those parts. In most cases, it is much better to use proven frameworks like Spring than create your own equivalent solution from a maintenance and applying the best practices perspective. For example, all spring templates (jdbc, rest, jpa etc.) have the following advantages -- perform common setup routines for you, let you skip the boilerplate and concentrate on the logic you want.
  • Spring MVC is probably not the best Web framework. There are other alternatives like Struts 2, Wicket, and JSF.  Having said this, Spring integrates well with the other Web frameworks like Struts, JSF, etc.
  • The XML files can get bloated. This can be minimized by carefully considering other options like annotations, JavaConfig, and having separate XML configuration files.

Q. What are the different types of IoC (dependency injection) ?
A. There are three types of dependency injection:

  • Constructor Injection (e.g. Spring): Dependencies are provided as constructor parameters.
  • Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
  • Interface Injection (e.g. Avalon): Injection is done through an interface.

Q. Have you used any other Dependency Injection (DI) frameworks?
A. Yes, Guice, Hivemind, and Seam.

11 comments:

  1. Thanks for this interview questions and answers.

    Interview Questions

    ReplyDelete
  2. Real good question and What I like most is detailed explanation. The main benefit offered by Spring is dependency Injection which leads to loosely coupled design and that has been clearly explained in point 1. By the way you can also see this list of spring questions asked in Java interviews for practice.

    ReplyDelete
  3. Really good article. Very detailed and unique one. Its really really helpful for a person like me who daily uses spring but unaware of its architecture details.

    Keep posting such articles. Great work !

    Regards,
    Amir

    ReplyDelete
  4. Dear Arulkumaran Kumaraswamipillai , I don't have much more knowledge to justify your work, or to suggest you something ,
    but just one thing i realized when i go through your all books ,blogs ,suggestions, you are God of Java :) your hard work pays not only to you , it pays to many one like me ....... God bless you .. and thanks a lot for your great work and also for your hard work. Your efforts are truly amazing and incredible ...... Thanks Again Arulkumaran Sir

    ReplyDelete

  5. Tks very much for post:

    I like it and hope that you continue posting.

    Let me show other source that may be good for community.

    Source: Hr sample interview questions

    Best rgs
    David

    ReplyDelete
  6. Dear ArulKumar

    am your fan i have more interest learn new technology, i learned all your Book i was gained
    lot of knowledge from your blogs thank you so much arulkumaran sir

    ReplyDelete
  7. What is Spring MVC ? What are the suitable request flow diagram of Spring MVC?

    ReplyDelete
  8. Learn the MVC web design pattern. Spring MVC is a web framework, like Struts.

    ReplyDelete
  9. refer http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html

    ReplyDelete