20+ Spring Interview Questions and Answers: Overview
Spring Interview Questions and Answers Q1 - Q14 are FAQs
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.
Q1. What do you understand by the terms Dependency Inversion Principle (DIP), Dependency Injection (DI) and Inversion of Control (IoC) container ?
A1.
- 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.
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.
Q2. In your experience, why would you use Spring framework?
A2.
- 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.
A3.
- 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.
Q4. What are the different types of IoC (dependency injection) ?
A4. 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.
- Spring Interview Questions and Answers : Spring Bean life cycle, DI, and IOC
- Understanding Spring bean scopes -- Singleton Vs. Prototype
- Spring Interview Questions and Answers: read properties file
- Spring and hibernate simple JDBC example
- Spring Interview Questions and Answers: Hibernate integration
- Spring Interview Questions and Answers: JNDI, JMS and Other
- Hibernate Interview Questions and Answers: with annotations and Spring framework
- Spring and Hibernate Interview Q&A: AOP, interceptors, and deadlock retry
- Batch processing in Java with Spring batch - part 1
- JSONP and jQuery with Spring MVC, RESTful Web Service and Maven
- CORS and jQuery with Spring MVC RESTful Web Service
Labels: Spring
22 Comments:
Thanks for this interview questions and answers.
Interview Questions
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.
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
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
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
Good tips
Web Designer in Bangalore
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
What is Spring MVC ? What are the suitable request flow diagram of Spring MVC?
Learn the MVC web design pattern. Spring MVC is a web framework, like Struts.
refer http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html
why do you think spring mvc is not considered as a good web framework?
I did not say it is bad. There are 15+ web frameworks in Java and some are more popular than the others. Each has its pros and cons. The current trend is to build single page RIA with JavaScript frameworks like AngularJS, HTML5, and CSS3.
I have question what is difference between java scheduler and spring scheduler
i am new to spring pls could you explain what is mean a pattern of injecting a class’s dependencies into it at runtime
start with a tutorial: http://java-success.blogspot.com.au/2012/10/spring-di-aka-ioc-tutorial.html there are more tutorials in this blog. Follow the links and use the search bar at the top.
There are different scheduling frameworks like Quartz, Spring task executor, etc to run a job asynchronously at a pre-determined time or interval, as a result of an event, etc.
thank you very much. i have senario to develope scheduler job class which can call a java program on daily basis and program internally call a webservice for this which is best frameworks develope schedular.
Have a look at Quartz. Also, check if your organization uses commercial tools like control-M.
thank you so much for replies. i want go with Quartz and i started sample programs and i found which is easy simple configuration changes. how avoid code changes which i am updating application context file everytime if want to change my schedular dates and timings.
i have created pool size minimum 1 and maximum 5 but i m getting this exception can you please advise on this
error : org.jboss.util.NestedSQLException: No ManagedConnections available within configured blocking timeout ( 30000 [ms] ); - nested throwable: (javax.resource.ResourceException: No ManagedConnections available within configured blocking timeout ( 30000 [ms] ))
What database are you using?
Why spring is not supporting interface injection?
Post a Comment
Subscribe to Post Comments [Atom]
<< Home