Spring Interview Questions | Java Development Journal

Spring Interview Questions

Spring Interview Questions

Read other articles of this series :

 

This post is the part of our Interview Questions series and in this post, we will discuss some of the commonly asked Spring interview questions during a job interview.

 

1. Spring Beans And Dependency Injection

Spring Beans are the core of Spring Framework. Some questions related to Spring Beans are:

 

Q1. What is the Spring Framework?

Spring is known as one of the most popular frameworks for Java Enterprise applications. Spring framework Dependency injection feature can be used on any Java based application (web or non-web).

The core of the Spring framework based on the dependency injection design pattern. This allows us to easily build decoupled systems.

 

Q2. What are the benefits of Spring?

Spring Framework makes it easier to build enterprise Java applications, below are some of the advantages of using it

  • IoC Container: Spring manage the life-cycle of the Spring Beans and configurations using it’s Ioc container, this makes project management and maintenance easier.
  • Versatile: Spring provides flexibility to integrate it with any Java based technologies.
  • Inversion of Control: Spring will take care of injecting the required dependencies for our application, we are no longer required to manually search and inject the required dependencies for our application.
  • Lightweight: Spring is divided into different modules with a minimal dependency on each other which make it really lightweight and have the flexibility to only use required modules for your application.
  • End to End Development: Spring Framework provides modules for all aspects of application development ranging from Dependency Injection, Persistence, Caching, Business, Web, REST, it’s an ecosystem for developing all type of Java based Enterprise applications.
  • Transaction Management: Framework provides abstraction and transparent layer for the transaction management. This provides a pluggable architecture where we can inject different transaction managers without changing the core system.
  • AOP: It supports Aspect-oriented programming(AOP).AOP addresses the problem of cross-cutting concerns.
  • Non-invasive: Spring does not force us to use any Spring based interface or to extend any Spring based class to use its features which give our code flexibility to be used in any other technology. e.g. We can inject dependency using @Inject annotation which is not Spring based annotation, there will be no change if we want to use Guice as our dependency injection API.
  • Exception Handling: Spring Framework provides multiple options to handle exceptions in a better and more flexible way.

 

Q3. What is Dependency Injection?

Dependency Injection is a technique with which we can make our program loosely coupled and inject required dependencies by defining them as Beans using several annotations like @Service, @Component, @Repository, @Controller or a @Bean annotation.

 

Q4. What are the different types of IOC containers available in Spring?

Spring Framework provides the following 2 types of containers.

  • BeanFactory Container: This is the base container available in the Spring Framework with support for Dependency Injection (DI).The org.springframework.beans and org.springframework.context packages are the basis for Spring Framework’s IoC container.
  • ApplicationContext Container: TheApplicationContext adds more enterprise-specific functionality. The ApplicationContext is a complete superset of the BeanFactory.

 

Q5. What are types of Dependency Injection techniques supported in Spring?

Spring supports three types of Dependency Injection

  • Setter-based Dependency Injection.
  • Constructor based Dependency Injection.
  • Field Injection

 

Q6. What does bean scopes Spring supports?

Spring support below 7 scopes. We can also define a custom scope if required.

  1. singleton
  2. prototype
  3. request
  4. session
  5. application
  6. websocket
  7. globalSession

For more details, read our article Spring Bean Scopes

 

Q7. Explain bean scopes in Spring?

Bean scopes define the lifecycle of a Bean.

  1. singleton(default*)
    Scopes a single bean definition for a single object instance per Spring IoC container.
  2. prototype
    Scopes a single bean definition for any number of object instances.
  3. request
    Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
  4. session
    Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
  5. global session
    Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

For more information read Spring Bean Scopes

 

Q8. What is the default scope of bean in Spring? How can we change the default scope in our application?

 By default, Spring beans are scoped singleton. To change the default bean scope in our application, we should implement the BeanFactoryPostProcessor interface and override the postProcessBeanFactory() method to set the desired bean scope.

public class CustomScopedPostProcessor implements BeanFactoryPostProcessor {

 public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException {
  for (String beanName: factory.getBeanDefinitionNames()) {
   BeanDefinition beanDefinition = factory.getBeanDefinition(beanName);

   beanDefinition.setScope("prototype");
  }
 }
}

 

Q9. How to create a custom scope in Spring?

As of Spring 2.0, the bean scoping mechanism in Spring is extensible. This means that you are not limited to just the bean scopes that Spring provides out of the box; you can define your own scopes. Read Custom Scope in Spring to learn how to create and use a custom scope in your application.

 

Q10. What is the recommended way to inject beans in Spring?

The recommended way to inject dependencies into Spring components is by using constructor injection. This should be followed by any compulsory dependencies needed. For optional dependencies, setter injection should be used.

 

Q11. What are the different modules/subprojects of the Spring?

  1. Spring Core.
  2. Spring JDBC
  3. ORM Module
  4. Spring AOP
  5. Spring MVC

 

Q12. What Design patterns are used in Spring framework?

  1. Singleton pattern in Singleton scoped beans
  2. Model View Controller in Spring MVC
  3. Data Access Object in Spring DAO support
  4. Front Controller in Spring Dispatcher Servlet
  5. Template Method Pattern in Spring JDBC support
  6. Adapter Pattern in Spring MVC and Spring Web
  7. Proxy Pattern in Spring AOP support
  8. Factory Pattern in Bean Factory classes

 

Q13. What are Spring profiles?

Spring profiles allow us to configure Spring Beans based on the profile of dev, QA, staging, production etc. The use of profiles is that we can make the same Spring app which points to different databases or message broker instances with a difference of just a flag. Please read our article on Spring Profiles for more detail.

 

Q14. What does @Required annotation do?

The @Required annotation applies to bean property setter methods. This annotation simply indicates that the affected bean property must be populated at configuration time. In case the required dependency is not available, the container will throw BeanInitializationException exception.

public class ShoppingCart {

 private CartService cartService;

 @Required
 public void setCartService(CartService cartService) {
  this.cartService = cartService;
 }

 // ...
}

 

Q15. What does @Autowired annotation do?

The @Autowired annotation is used with fields or methods for injecting a bean by type. This annotation allows Spring to resolve and inject collaborating beans into the required bean.

 

Q16. What does @Qualifier annotation do?

The @Qualifier annotation helps to avoid confusion when there are multiple instances of the same bean type present in the system. Let’s take an where two beans implement our “CartService” interface.

public interface CartService {
 public void addToCart();
}

@Component(value = "cartService")
public class DefaultCartService implements CartService {

 @Override
 public void addToCart() {
  System.out.println("Add to cart");
 }
}

@Component(value = "customCartService")
public class CustomCartService implements CartService {

 @Override
 public void addToCart() {
  System.out.println("custom add to cart service");
 }
}

This annotation works closely with @Autowired annotation. To inject CustomCartService in our AddToCartService, we use @Autowired with @Qualifier annotation. If we don’t use @Qualifier, Spring throws NoUniqueBeanDefinitionException.

@Component
public class AddToCartService {

    @Autowired
    @Qualifier("customCartService")
    private CartService cartService;

    public void addToCart() {
         cartService.addToCart();
}

 

Q17. What does @Primary annotation do? What is it’s importance?

The @Primarary annotation indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one ‘primary’ bean exists among the candidates, it will be the autowired value.

To understand it, let’s take the same example as outlined in Q16

public interface CartService {
 public void addToCart();
}

@Component
public class DefaultCartService implements CartService {

 @Override
 public void addToCart() {
  System.out.println("Add to cart");
 }
}

@Primary
@Component
public class CustomCartService implements CartService {

 @Override
 public void addToCart() {
  System.out.println("custom add to cart service");
 }
}

Because CustomerCartService is marked with @Primary, it will be injected preferentially over theDefaultCartService variant assuming both are present as beans within the same Spring application context.

 

Q18. In how many ways we can handle Exceptions in a Spring project?

  1. By using @ExceptionHandler annotation at the Controller level. This helps in managing an exception in a particular controller without affecting complete app flow.
  2. Using HandlerExceptionResolver, we can handle exceptions at the complete application level.
  3. By using @ControllerAdvice annotation, we can configure Exception handlers for application-level control and still keep the code very clean and modular.

 

Q19. What is the difference between annotations like @Component, @Controller, @Service, and @Repository?

Out of all, @Component annotation is a generic annotation. So anything which is a Controller, Service or a Repository, it’s a Component as well. For specifics, let’s look at each of one of these:

  • @Controller: This annotation enables the detection of @RequestMapping annotation in the class. It also indicates that this class is a Controller.
  • @Service: It indicates that this class handles the business logic of the application and ought to call the @Repository classes for DB interaction.
  • @Repository: This indicates that the class defines a DB interface. It makes sure that the platform-specific exceptions caught again and thrown again as Spring specific unchecked exceptions.

 

Q20. What is the difference between the Singleton Design Pattern and Spring Singleton scope?

There is a minimal similarity between Singleton Design Pattern and Spring Singleton Scope. Singleton Design Pattern as defined in the Gang of Four(GoF) books refer to the scope of the object of only one instance per ClassLoader. The scope of Spring Singleton bean referred to as “a single instance per bean and per container”. To understand it more clearly, let’s take a look at the below example


<!-- Singlton is the default scope, you can skip scope attribute in below declaration--!>
<bean id="bean1" class="com.javadevjournal.SingletonBean" scope="singleton"/>
<bean id="bean2" class="com.javadevjournal.SingletonBean" scope="singleton"/>

In the above example, Spring Container will create 2 instances of our SingletonBean class, to put it, in other words, Spring container will create 2 instances of our class and bind them with the “id” and store them in singleton cache. Any call for the system with id=”bean1″ will return bean instance from singleton cache bind with Id “bean1” and call for id=”bean2″ will return instance bind with id “bean2”.

Read Spring Singleton vs Singleton Pattern for more detail.

 

Q21. What is a Spring Bean?

The objects that form the backbone of your application and that managed by the Spring IoC container is known as beans. The Spring Beans are Java Objects that are initialized by the Spring IoC container. Any normal Java POJO class can be a Spring Bean if it’s configured to be initialized via container by providing configuration metadata information.

 

Q22. What is an ApplicationContext?

ApplicationContext is the main interface responsible to provide configurations for an application.ApplicationContext is in read-only mode while the application is running. Here is the list of features supported by ApplicationContext.

  • Bean factory methods for accessing application components.
  • The ability to publish events to registered listeners
  • Inheritance from a parent context.
  • The ability to load file resources in a generic fashion.

Spring Framework provides a number of implementations of the ApplicationContext interface.

 

Q23. What is the difference between BeanFactory and ApplicationContext?

Both BeanFactory and ApplicationContext are IOC container provided by Spring.BeanFacotory is also known as basic IOC while ApplicationContext is known as advance IOC.ApplicationContext includes all functionality of the BeanFactory and provided extra features. Below are few differences between BeanFactory and ApplicationContext.

FeatureApplicationContextBeanFactory
Bean instantiation/wiringYesYes
Automatic BeanPostProcessor registrationYesNo
Automatic BeanFactoryPostProcessor registrationYesNo
Convenient MessageSource access (for i18n)YesNo
ApplicationEvent publicationYesNo

BeanFactory uses lazy initialization approach while ApplicationContext is based on eager initialization.

Because the ApplicationContext includes all functionality of the BeanFactory, it is generally recommended over the BeanFactory.

 

Q24. Explain the Spring bean lifecycle?

Spring bean managed by Spring IOC based on the XML or Java configuration. The Spring beans creation, management, and disposal handled by the Spring IoC. At a high-level Spring Bean pass through a different life cycle.

  • Required to perform some initialization to get it into a usable state.
  • Populate properties: Spring IoC container injects the bean’s properties.
  • Post Initialize : Spring container calls their postProcessAfterinitalization() method.
  • If a bean is no longer required, it will be removed from the IoC container.

Here is a complete lifecycle of Spring Bean (Source: dineshonjava)

Spring-Bean-Life-Cycle

 

 

Q25. Can we use multiple Spring configuration files in one project?

Yes, there are a number of different ways to achieve this. We can load multiple beans configurations while creating the application context

ApplicationContext context = 
    	new ClassPathXmlApplicationContext(new String[] {"file1.xml",
              "file2.xml","file3.xml"});

Above approach is not flexible and error-prone. The recommended way is to create use <import> tag to combine multiple files into the single XML file.

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

   <!-- Load additional configuration -->
   <import resource="spring-filter-config.xml"/>
   <import resource="spring-security-config.xml"/>
   <import resource="spring-mvc-config.xml"/>
</beans>

We can also use Java-based configurations for multiple files.

@Configuration
@Import({
 MainConfig.class,
 Config1.class,
 Config2.class
})
public class ApplicationConfig { ....}

 

Q26. Does Spring Bean provide thread safety?

The short answer is “No. Spring works with different bean scopes but they work and define bean lifecycle when the bean is created. Spring bean scope should not be seen with thread safety as they have very little relation to thread safety. Thread safety of the Spring bean is based on the design of the application and how a given bean is used. Spring introduced a new SimpleThreadScope which is a thread-based Scope.

We can make a careful choice while using Spring scoped bean in a multi-thread environment. For example in the HTTP request, we can use the “request” scope to make sure a new bean is created for each HTTP request. (remember even this approach is not thread safe).

 

Q27. What is Autowiring? What are the different Autowiring modes available in Spring?

The Spring container can autowire relationships between collaborating beans. You can let Spring resolve collaborators (other beans) automatically for your bean by inspecting the contents of the ApplicationContext. Spring Framework supports following Autowiring modes.

  • no – (Default) No autowiring. Bean references must be defined by ref elements. 
  • byName – Autowiring by property name. Spring looks for a bean with the same name as the property that needs to be autowired.
  • constructor – Applies to constructor arguments.
  • byType – Lets a property be autowired if exactly one bean of the property type exists in the container

 

Q28. What are the limitations of autowiring?

Spring autowiring is a powerful technique with a number of advantages, however, this technique carries certain limitations

  • Dependencies specified using constructor and property based setting will always override autowiring. We can’t autowire simple properties such as primitives, Strings, and Classes.
  • This can be confusing if we have a number of dependencies defined in our program.
  • Autowiring is less exact than explicit wiring since Spring container use certain assumption while trying to match the bean during autowiring.

 

Q29. What is the Spring Java-Based Configuration?

There are multiple ways to configure Spring based application. Spring Java-based configuration provides a type-safe configuration, also known as an alternative to traditional XML based configuration.

Please read for Spring WebApplicationInitializer more detail.

 

Q30. What is spring annotation based configuration??

Spring framework also provides the option to define bean autowiring using annotations.we can use @Component,@Repository,@Service, @Required and @Controller etc. annotation to configure bean in the Spring application. To enable this, we need to add following entry in our application.

<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
	<context:annotation-config/>
</beans>

only looks for annotations on beans in the same application context in which it is defined. This means that, if you put in a WebApplicationContext for a DispatcherServlet, it only checks for @Autowired beans in your controllers, and not your services

 

Q31. What are Spring events? describe some of the standard Spring events?

Spring Events are part of the Spring Framework. Events are used to communicate application status change among different systems. There are numbers of events available with Spring Framework.

  • ContextRefreshedEvent – This event published when the ApplicationContext is either initialized or refreshed. This is also available when on using refresh() method on the ConfigurableApplicationContext interface.
  • ContextStartedEvent – Event published when the ApplicationContext started using the start() method.
  • ContextStoppedEvent – Event published when the ApplicationContext stopped using the stop() method on the ConfigurableApplicationContext interface.
  • ContextClosedEvent –  Event raised when an ApplicationContext gets closed.

 

Q32. What is Spring Security?

Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications. Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Here is the list of some of the most common features of Spring security.

  • Support for Authentication and Authorization.
  • Out of the box support for CSRF, session fixation etc.
  • OOTB integration with Spring MVC.
  • Support to integrate external authentication systems.

 

Spring MVC

In this section of Spring interview questions, we are compiling some of the most commonly asked questions during Spring MVC interview.

Q33. What is the @Autowired annotation?

The @Autowired annotation used to inject Spring dependencies. Spring Framework provided the following type of bean autowiring.

  • Setter-based autowiring.
  • Constructor based bean wiring.
  • Field or property based autowiring.

For more detail, read Spring Bean @Autowired

 

Q34. What is a Controller in Spring MVC?

Controllers are responsible for controlling the flow of the application execution. In Spring MVC architecture the DispatcherServlet works as Front Controller.DispatcherServlet process the request and pass request to the controller class annotated with @Controller.Each controller class is responsible to handle one or more requests of a certain type.

For more detail, read Introduction to Spring Controllers

 

Q35. How to get ServletContext and ServletConfig in a Spring Bean?

There are two options for getting ServletContext and ServletConfig in a Spring Bean.

  • Use @Autowired annotation to inject ServletContext and ServletConfig in Spring Bean.
  • Implement Spring aware interfaces in the class that depends on ServletConfigor ServletContext

Using @Autowired annotation

@Autowired
ServletContext servletContext;
@Autowired
ServletConfig servletConfig;

Implementing Spring aware interfaces

public class ServletConfigAwareClass implements ServletConfigAware {

 private ServletConfig config;

 public void setServletConfig(ServletConfig servletConfig) {
  this.config = servletConfig;
 }

For more details, see ServletConfigAware

 

Q36. Explain the working of @RequestMapping?

The @RequestMapping is used to map web request to the controller in Spring MVC application. The @RequestMapping annotation can be applied to class-level and/or method-level in a controller.

 

Q37. What is ViewResolver in Spring?

The ViewResolver let SPring MVC application to render models in a browser without binding to specific view technology (e.g. JSP  or Thymeleaf). This works by providing a mapping between view names and actual views.View addresses the preparation of data before handing over to a specific view technology.

 

Q38. What is Spring MVC Interceptor and how to use it?

Interceptors are useful to intercept the client request and process it. There are three options to intercept client request using Spring interceptors.

  • preHandle
  • postHandle
  • afterComplete (after the view is rendered to the client)

Interceptors are useful for cross-cutting concerns and help us to avoid duplicate code (e.g logging, profiling etc.).We can create spring interceptor by implementing a HandlerInterceptor interface or by extending abstract class HandlerInterceptorAdapter.

 

Q39. How to handle exceptions in Spring MVC?

Spring MVC provides the following three options for exception handling

  1. @ExceptionHandler Annotation – ExceptionHandler is a Spring annotation handle exceptions thrown by request handling. This annotation works at the @Controller level.
  2. @ControllerAdvice Annotation – This annotation supports global Exception handler mechanism. A controller advice allows you to use exactly the same exception handling techniques but applies them across the application, not just to an individual controller.
  3. HandlerExceptionResolver – Resolve any exception thrown by the application.

For more information please read

 

Q40. How to validate form data in Spring Web MVC?

Spring provides built-in support to use JSR-303 based bean validation. For using JSR-303 based validation, we need to annotate bean variables with the required validations.Let’s take a simple example to validate customer object

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class Customer {

 @NotNull
 @Size(min = 2, max = 30)
 private String name;

 @NotNull
 @Min(18)
 private Integer age;

 //getter and setters

}

To trigger JSR-303 based validation, we only need to annotate our incoming object with @Valid annotation

@Controller
public class WebController {

 @PostMapping("/")
 public String checkPersonInfo(@Valid Customer customer, BindingResult bindingResult) {

  if (bindingResult.hasErrors()) {
   return "form";
  }

  return "redirect:/results";
 }
}

Spring validation also provides an interface that can be used to create custom validators (ina case out of the box validator does not satisfy the requirements.)

 

In this article, we discussed some of the commonly asked Spring interview questions during a job interview. We will be covering Interview questions of the other modules of the Spring framework in a different post.

Umesh

Hello!! I am Umesh- an engineer by profession and a photographer by passion.I like to build stuff on the web using OSS and love to capture the world through my lens.

follow me on:

3
Leave a Reply

avatar
2 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
Umesh AwasthiRobert Recent comment authors

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
newest oldest most voted
Notify of
Robert
Guest
Robert

Thanks for compiling these questions, really helpful

Umesh Awasthi
Admin
Umesh Awasthi

Thanks, Robert !!

trackback
Spring Boot Interview Questions | Java Development Journal

[…] Spring Interview Questions […]