Spring Interview Questions [2021]

Spring Interview Questions and Answers

  1. What is Spring? Spring is an open source development framework for Enterprise Java.Spring framework core concepts are “Dependency Injection” and “Aspect Oriented Programming”.Spring framework can be used in normal java applications also to achieve loose coupling between different components by implementing dependency injection and we can perform cross cutting tasks such as logging and authentication using spring support for aspect oriented programming.It is a lightweight, loosely coupled and integrated framework for developing enterprise applications in java.
  2. What are benefits of Spring Framework?
    • Lightweight: Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.
    • Inversion of control (IOC): Loose coupling is achieved in Spring, with the Inversion of Control technique. The objects give their dependencies instead of creating or looking for dependent objects.
    • Aspect oriented (AOP): Spring supports Aspect oriented programming and separates application business logic from system services.
    • Container: Spring contains and manages the life cycle and configuration of application objects.
    • MVC Framework: Spring’s web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks.
    • Transaction Management: Spring provides a consistent transaction management interface that can scale down to a local transaction and scale up to global transactions (JTA).
    • Exception Handling: Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO) into consistent, unchecked exceptions.
  3. What do you understand by Dependency Injection? Dependency Injection design pattern allows us to remove the hard-coded dependencies and make our application loosely coupled, extendable and maintainable. We can implement dependency injection pattern to move the dependency resolution from compile-time to runtime.Spring framework provides two ways to inject dependency
    • Constructor-based dependency injection: Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.
    • Setter-based dependency injection: Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.
  4. What are the modules of spring framework? Some of the important Spring Framework modules are:
    • Spring Context – for dependency injection.
    • Spring AOP – for aspect oriented programming.
    • Spring DAO – for database operations using DAO pattern
    • Spring JDBC – for JDBC and DataSource support.
    • Spring ORM – for ORM tools support such as Hibernate
    • Spring Web Module – for creating web applications.
    • Spring MVC – Model-View-Controller implementation for creating web applications, web services etc.
  5. What is IoC Container? The IoC container is responsible to instantiate, configure and assemble the objects. The IoC container gets informations from the XML file and works accordingly. The main tasks performed by IoC container are:
    • to instantiate the application class
    • to configure the object
    • to assemble the dependencies between the objectsThere are two types of IoC containers. They are:
    1. BeanFactory
    2. ApplicationContext
  6. What is the difference between Bean Factory and ApplicationContext? BeanFactory is also called basic IOC and ApplicationContext is called Advanced IOC. Although BeanFactory and ApplicationContext both are used to get the beans from IOC container by using method getBean(String beanName). But they have some significant differences in their implementation which are described as below :
    1. BeanFactory uses lazy initialization approach whereas ApplicationContext uses eager initialization approach.i.e BeanFactory creates a singleton bean only when it is requested from it but ApplicationContext creates all singleton beans at the time of its own initialization.
    2. ApplicationContext supports internationalization but BeanFactory do not.
    3. Annotation based dependency Injection is not supported by BeanFactory whereas ApplicationContext supports using annotation @PreDestroy, @Autowired.
    4. The ApplicationContext interface is built on top of the BeanFactory interface. It adds some extra functionality than BeanFactory such as simple integration with Spring’s AOP, message resource handling (for I18N), event propagation, application layer specific context (e.g. WebApplicationContext) for web application. So it is better to use ApplicationContext than BeanFactory.
  7. In which scenario, you will use singleton and prototype scope? Singleton scope should be used with EJB stateless session bean and prototype scope with EJB stateful session bean.
  8. Explain the Spring MVC module.MVC framework is provided by Spring for building web applications. Spring can easily be integrated with other MVC frameworks, but Spring’s MVC framework is a better choice, since it uses IoC to provide for a clean separation of controller logic from business objects. With Spring MVC you can declaratively bind request parameters to your business objects.For more details Spring MVC Flow
  9. What is Spring configuration file? Spring configuration file is an XML file. This file contains the classes information and describes how these classes are configured and introduced to each other.
  10. How do you define the scope of a bean?When defining a <bean> in Spring, we can also declare a scope for the bean. It can be defined through the scope attribute in the bean definition. For example, when Spring has to produce a new bean instance each time one is needed, the bean’s scope attribute to be prototype. On the other hand, when the same instance of a bean must be returned by Spring every time it is needed, the the bean scope attribute must be set to singleton.
  11. What are the different bean scopes in spring?There are five scoped provided by the Spring Framework supports following five scopes:
    • In singleton scope, Spring scopes the bean definition to a single instance per Spring IoC container.It is the default scope.
    • In prototype scope, a single bean definition has any number of object instances.
    • In request scope, a bean is defined to an HTTP request. This scope is valid only in a web-aware Spring ApplicationContext.
    • In session scope, a bean definition is scoped to an HTTP session. This scope is also valid only in a web-aware Spring ApplicationContext.
    • In global-session scope, a bean definition is scoped to a global HTTP session. This is also a case used in a web-aware Spring ApplicationContext.
  12. Are Singleton beans thread safe in Spring Framework?No, singleton beans are not thread-safe in Spring framework.
  13. Which ViewResolver class is widely used?The org.springframework.web.servlet.view.InternalResourceViewResolver class is widely used.
  14. What’s the difference between @Component, @Controller, @Repository & @Service annotations in Spring?@Component is used to indicate that a class is a component. These classes are used for auto detection and configured as bean, when annotation based configurations are used.@Controller is a specific type of component, used in MVC applications and mostly used with RequestMapping annotation.@Repository annotation is used to indicate that a component is used as repository and a mechanism to store/retrieve/search data. We can apply this annotation with DAO pattern implementation classes.@Service is used to indicate that a class is a Service. Usually the business facade classes that provide some services are annotated with this.We can use any of the above annotations for a class for auto-detection but different types are provided so that you can easily distinguish the purpose of the annotated classes.
  15. What is DispatcherServlet and ContextLoaderListener?DispatcherServlet is the front controller in the Spring MVC application and it loads the spring bean configuration file and initialize all the beans that are configured. If annotations are enabled, it also scans the packages and configure any bean annotated with @Component, @Controller, @Repository or @Service annotations.ContextLoaderListener is the listener to start up and shut down Spring’s root WebApplicationContext. It’s important functions are to tie up the lifecycle of ApplicationContext to the lifecycle of the ServletContext and to automate the creation of ApplicationContext. We can use it to define shared beans that can be used across different spring contexts.
  16. What is ViewResolver in Spring?ViewResolver implementations are used to resolve the view pages by name. Usually we configure it in the spring bean configuration file. For example:Java0123456           <!– Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory –><beans:bean class=”org.springframework.web.servlet.view.InternalResourceViewResolver”> <beans:property name=”prefix” value=”/WEB-INF/views/” /> <beans:property name=”suffix” value=”.jsp” /></beans:bean> InternalResourceViewResolver is one of the implementation of ViewResolver interface and we are providing the view pages directory and suffix location through the bean properties. So if a controller handler method returns “home”, view resolver will use view page located at /WEB-INF/views/home.jsp.
  17. How to handle exceptions in Spring MVC Framework?Spring MVC Framework provides following ways to help us achieving robust exception handling.
    1. Controller Based – We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation.
    2. Global Exception Handler – Exception Handling is a cross-cutting concern and Spring provides @ControllerAdvice annotation that we can use with any class to define our global exception handler.
    3. HandlerExceptionResolver implementation – For generic exceptions, most of the times we serve static pages. Spring Framework provides HandlerExceptionResolver interface that we can implement to create global exception handler. The reason behind this additional way to define global exception handler is that Spring framework also provides default implementation classes that we can define in our spring bean configuration file to get spring framework exception handling benefits.
  18. How to create ApplicationContext in a Java Program?There are following ways to create spring context in a standalone java program.
    1. AnnotationConfigApplicationContext: If we are using Spring in standalone java applications and using annotations for Configuration, then we can use this to initialize the container and get the bean objects.
    2. ClassPathXmlApplicationContext: If we have spring bean configuration xml file in standalone application, then we can use this class to load the file and get the container object.
    3. FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.
  19. What are the minimum configurations needed to create Spring MVC application?For creating a simple Spring MVC application, we would need to do following tasks.
    • Add spring-context and spring-webmvc dependencies in the project.
    • Configure DispatcherServlet in the web.xml file to handle requests through spring container.
    • Spring bean configuration file to define beans, if using annotations then it has to be configured here. Also we need to configure view resolver for view pages.
    • Controller class with request mappings defined to handle the client requests.Above steps should be enough to create a simple Spring MVC application.
  20. What are some of the important Spring annotations you have used?Some of the Spring annotations that I have used in my project are:
    • @Controller – for controller classes in Spring MVC project.
    • @RequestMapping – for configuring URI mapping in controller handler methods. This is a very important annotation.
    • @ResponseBody – for sending Object as response, usually for sending XML or JSON data as response.
    • @PathVariable – for mapping dynamic values from the URI to handler method arguments.
    • @Autowired – for autowiring dependencies in spring beans.
    • @Qualifier – with @Autowired annotation to avoid confusion when multiple instances of bean type is present.
    • @Service – for service classes.
    • @Scope – for configuring scope of the spring bean.
    • @Configuration@ComponentScan and @Bean – for java based configurations.
    • AspectJ annotations for configuring aspects and advices, @Aspect@Before@After@Around@Pointcut etc.
  21. Can we send an Object as the response of Controller handler method?Yes we can, using @ResponseBody annotation. This is how we send JSON or XML based response in restful web services.
  22. What is Spring DAO?Spring DAO support is provided to work with data access technologies like JDBC, Hibernate in a consistent and easy way. For example we have JdbcDaoSupportHibernateDaoSupportJdoDaoSupport and JpaDaoSupport for respective technologies.Spring DAO also provides consistency in exception hierarchy and we don’t need to catch specific exceptions.
  23. Name some of the design patterns used in Spring Framework?Spring Framework is using a lot of design patterns, some of the common ones are:
    1. Singleton Pattern: Creating beans with default scope.
    2. Factory Pattern: Bean Factory classes
    3. Prototype Pattern: Bean scopes
    4. Adapter Pattern: Spring Web and Spring MVC
    5. Proxy Pattern: Spring Aspect Oriented Programming support
    6. Template Method Pattern: JdbcTemplate, HibernateTemplate etc
    7. Front Controller: Spring MVC DispatcherServlet
    8. Data Access Object: Spring DAO support
    9. Dependency Injection and Aspect Oriented Programming
  24. What are the types of the transaction management Spring support?Spring supports two types of transaction management:
    • Programmatic transaction management: This means that you have managed the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain.
    • Declarative transaction management: This means you separate transaction management from the business code. You only use annotations or XML based configuration to manage the transactions.
  25. What are the benefits of the Spring Framework’s transaction management?
    • It provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO.
    • It provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA.
    • It supports declarative transaction management.
    • It integrates very well with Spring’s various data access abstractions.
  26. Which Transaction management type is more preferable?Most users of the Spring Framework choose declarative transaction management because it is the option with the least impact on application code, and hence is most consistent with the ideals of a non-invasive lightweight container. Declarative transaction management is preferable over programmatic transaction management though it is less flexible than programmatic transaction management, which allows you to control transactions through your code.
  27. What is the difference between Spring AOP and AspectJ AOP?AspectJ is the industry-standard implementation for Aspect Oriented Programming whereas Spring implements AOP for some cases. Main differences between Spring AOP and AspectJ are:
    • Spring AOP is simpler to use than AspectJ because we don’t need to worry about the weaving process.
    • Spring AOP supports AspectJ annotations, so if you are familiar with AspectJ then working with Spring AOP is easier.
    • Spring AOP supports only proxy-based AOP, so it can be applied only to method execution join points. AspectJ support all kinds of pointcuts.
    • One of the shortcoming of Spring AOP is that it can be applied only to the beans created through Spring Context.
  28. What is the importance of Spring bean configuration file?We use Spring Bean configuration file to define all the beans that will be initialized by Spring Context. When we create the instance of Spring ApplicationContext, it reads the spring bean xml file and initialize all of them. Once the context is initialized, we can use it to get different bean instances.Apart from Spring Bean configuration, this file also contains spring MVC interceptors, view resolvers and other elements to support annotations based configurations.
  29. Explain Bean lifecycle in Spring framework?
    • The spring container finds the bean’s definition from the XML file and instantiates the bean.
    • Spring populates all of the properties as specified in the bean definition (DI).
    • If the bean implements BeanNameAware interface, spring passes the bean’s id to setBeanName()method.
    • If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory()method.
    • If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method.
    • If the bean implements IntializingBean, its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called.
    • If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
    • If the bean implements DisposableBean, it will call the destroy() method.
  30. Which are the important beans lifecycle methods?There are two important bean lifecycle methods. The first one is setup which is called when the bean is loaded in to the container. The second method is the teardown method which is called when the bean is unloaded from the container.The bean tag has two important attributes (init-method and destroy-method) with which you can define your own custom initialization and destroy methods. There are also the correspondive annotations(@PostConstruct and @PreDestroy).
  31. How can you inject a Java Collection in Spring?Spring offers the following types of collection configuration elements:
    • The <list> type is used for injecting a list of values, in the case that duplicates are allowed.
    • The <set> type is used for wiring a set of values but without any duplicates.
    • The <map> type is used to inject a collection of name-value pairs where name and value can be of any type.
    • The <props> type can be used to inject a collection of name-value pairs where the name and value are both Strings.
  32. What is bean wiring?Wiring, or else bean wiring is the case when beans are combined together within the Spring container. When wiring beans, the Spring container needs to know what beans are needed and how the container should use dependency injection to tie them together.
  33. What is bean auto wiring?The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for a bean by inspecting the contents of the BeanFactory without using <constructor-arg> and <property> elements.
  34. Explain different modes of auto wiring?The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for dependency injection:
    • no: This is default setting. Explicit bean reference should be used for wiring.
    • byName: When autowiring byName, the Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file.
    • byType: When autowiring by datatype, the Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exist, a fatal exception is thrown.
    • constructor: This mode is similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.
    • autodetect: Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.
  35. Are there limitations with autowiring?Limitations of autowiring are:
    • Overriding: You can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring.
    • Primitive data types: You cannot autowire simple properties such as primitives, Strings, and Classes.
    • Confusing nature: Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring.
  36. What are some of the best practices for Spring Framework?Some of the best practices for Spring Framework are:
    1. Avoid version numbers in schema reference, to make sure we have the latest configs.
    2. Divide spring bean configurations based on their concerns such as spring-jdbc.xml, spring- security.xml.
    3. For spring beans that are used in multiple contexts in Spring MVC, create them in the root context and initialize with listener.
    4. Configure bean dependencies as much as possible, try to avoid autowiring as much as possible.
    5. For application level properties, best approach is to create a property file and read it in the spring bean configuration file.
    6. For smaller applications, annotations are useful but for larger applications annotations can become a pain. If we have all the configuration in xml files, maintaining it will be easier.
    7. Use correct annotations for components for understanding the purpose easily. For services use @Service and for DAO beans use @Repository.
    8. Spring framework has a lot of modules, use what you need. Remove all the extra dependencies that gets usually added when you create projects through Spring Tool Suite templates.
    9. If you are using Aspects, make sure to keep the join pint as narrow as possible to avoid advice on unwanted methods. Consider custom annotations that are easier to use and avoid any issues.
    10. Use dependency injection when there is actual benefit, just for the sake of loose-coupling don’t use it because it’s harder to maintain.
  37. What are differences between Setter Injection and Constructor Injection? Refer our article on Difference between Setter Injection and Constructor Injection