Spring Interview Questions

[thrive_toggles_group”][thrive_toggles title=”Read other articles of this series:” no=”1/1″]

[/thrive_toggles][/thrive_toggles_group]

 [toc] 

This post is the part of our Interview Questions series and in this post, we will discuss some commonly asked Spring interview questions during a job interview. Spring Beans are the core of Spring Framework. Some interview questions on Spring related to Spring Beans are:

 

Q1. What is the Spring Framework?

Spring is one the most popular frameworks for enterprise applications.The core of the Spring framework based on the dependency injection design pattern which allows us to build decoupled systems.

 

Q2. What are the benefits of Spring?

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

  • IoC Container: Spring manage the life-cycle of the Spring Beans and configurations using its 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 comprises different modules with a minimal dependency on each other which make it lightweight and flexible to only use the 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 flexibility to use it with 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 is Spring IOC containers?

Spring IoC container is the central management system of the Spring Framework. It is responsible to create, configure and manage the life cycle of these objects. The container gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata provided in the form of either XML configurations or annotations.It allows you to express the objects that compose your application and the rich interdependencies between such objects.

Spring IoC container

 

Q5. What are the different 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.

 

Q6. 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

 

Q7. What beans 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

 

Q8. Explain bean scopes in Spring?

Bean scopes define the life cycle 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 many object instances.
  3. request
    Scopes a single bean definition to the life-cycle of a single HTTP request; that is each HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in a web-aware Spring ApplicationContext.
  4. session
    Scopes a single bean definition to the life-cycle of an HTTP Session. Only valid in a web-aware Spring ApplicationContext.
  5. global session
    Scopes a single bean definition to the life-cycle of a global HTTP Session. Typically, only valid when used in a portlet context. Only valid in a web-aware Spring ApplicationContext.

For more information, read Spring Bean Scopes

 

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

By default, Spring beans are singleton scope. 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");
  }
 }
}

 

Q10. How to create a custom scope in Spring?

As of Spring 2.0, the bean scoping mechanism in Spring is extensible. This means it does not limit you 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.

 

Q11. 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 followed by any compulsory dependencies needed. For optional dependencies, use the setter injection.

 

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

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

Here is a high-level overview of Spring modules:

Spring Framework ModulesQ13. 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

 

Q14. What are Spring profiles?

Spring profiles allow us to configure Spring Beans based on the profile of dev, QA, staging, production, etc. With Spring profile, 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.

 

Q15. What does @Required annotation do?

The @Required annotation applies to bean property setter methods. This annotation shows 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;
 }

 // ...
}

 

Q16. 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.

 

Q17. What does @Qualifier annotation do?

The @Qualifier annotation helps when there are many instances of the same bean. Let’s take an example where two beans implement same 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();
}

 

Q18. What does @Primary annotation do? What is its importance?

The @Primarary annotation shows it should give a bean preference when multiple candidates are qualified to autowire.

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.

 

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

  1. By using @ExceptionHandler annotation at the Controller level.
  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.

 

Q20. 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. For specifics, let’s look at each of one of these:

  • @Controller: This annotation enables the detection of @RequestMapping annotation in the class.
  • @Service: It shows that this class handles the business logic of the application and ought to call the @Repository classes for DB interaction.
  • @Repository: This shows 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.

 

Q21. 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. Spring Singleton bean referred to as “a single instance per bean and per container”. To understand it more, let’s 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.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.

 

Q22. What is a Spring Bean?

The objects that form the foundation of your application and managed by the Spring container is known as beans. The Spring Beans are Java Objects loaded by the Spring IoC container. Any normal Java POJO can be a Spring Bean if initialization via Spring container.

 

Q23. What is an ApplicationContext?

ApplicationContext is the main interface to provide application configurations.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.
  • During application run, it wroks in read-only mode.

Spring Framework provides several implementations of the ApplicationContext interface.

 

Q24. What is the difference between BeanFactory and ApplicationContext?

Both 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.

Feature ApplicationContext BeanFactory
Bean instantiation/wiring Yes Yes
Automatic BeanPostProcessor registration Yes No
Automatic BeanFactoryPostProcessor registration Yes No
Convenient MessageSource access (for i18n) Yes No
ApplicationEvent publication Yes No

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

[pullquote align=”normal”]Because the ApplicationContext includes all functionality of the BeanFactory, they recommend it over the BeanFactory.[/pullquote]

 

Q25. Explain the Spring bean life-cycle?

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 do 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, the container will remove it.

Here is a complete life-cycle of Spring Bean (Source: dineshonjava)

Spring-Bean-Life-Cycle

 

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

Yes, there are many ways to do this. We can load multiple beans configurations while setting up 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 { ....}

 

Q27. Does Spring Bean provide thread safety?

The short answer is “No”. Spring works with different bean scopes but they work and define bean life-cycle when the bean is created. Do not look at the Spring bean scope with thread safety as they have little relation to thread safety. Thread safety of the Spring bean is based on the design of the application and how a 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 it creates a new bean for each HTTP request. (remember even this approach is not thread safe).

 

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

The Spring container can autowire relationships between participating beans by scanning the ApplicationContext.It aids the following modes

  • no – (Default) No autowiring. Ref elements must define bean references.
  • 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

 

Q29. What are the limitations of autowiring?

Spring autowiring is a powerful technique with several 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 confuse if we have several dependencies defined in our program.
  • Autowiring is less exact than explicit wiring since Spring container use a certain assumption while trying to match the bean during autowiring.

 

Q30. What is the Spring Java-Based Configuration?

Spring Java-based configuration gives a type-safe configuration, also known as alternative to XML based configuration.

Please read for Spring WebApplicationInitializer more detail.

 

Q31. 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 the 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>

[pullquote align=”normal”] 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 [/pullquote]

 

Q32. What are Spring events? describe standard Spring events?

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

  • ContextRefreshedEvent – This event published when the ApplicationContext initialized or refreshed. This is also available when on using refresh() method on the ConfigurableApplicationContext interface.
  • ContextStartedEvent – Event published when the ApplicationContext used 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.

 

Q33. 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.

 

Q34. What is the @Autowired annotation?

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

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

 

Thi section of Spring framework interview questions, covers Spring’s Data access module.

Q35. What is the Spring DAO?

The DAO or Data Access Object in Spring provides support to work with JDBC, Hibernate and JPA. DAO layer is an abstraction from Spring framework which allows us to work on these data technologies in a consistent way without getting into the low-level details.

 

Q36. How to enable transactions with Spring?

Spring provides a consistent abstraction for transaction management. Spring offers declarative and programmatic transaction (with annotations or by using Aspect Oriented Programming). Declarative transaction management is most flexible and works in most of the use cases. To use this approach, use the @Transactional annotation. We also need to define the transaction manager for the DataSource.

<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>

Here are benefits of using the Spring Transactions:

  1. Consistent programming model across different transaction APIs (e.g. JTA, JDBC, JPA etc.)
  2. Excellent integration with Spring’s data access abstractions.
  3. Support for declarative and programmatic transaction

 

Q37. What is Spring JdbcTemplate class and how to use it?

The Spring JdbcTemplate class provides an abstraction around the JDBC operations and helps to avoid common errors. Below are common tasks taken care by JdbcTemplate class:

  1. Handling JDBC connections.
  2. Working on the ResultSet.
  3. execute SQL queries.  

If you are using Spring Boot, add “spring-boot-starter-jdbc” to enable support using auto-configuration. For non Spring boot project, add a simple configuration for DataSource:

@Configuration
public class CustomJdbcConfig {
    @Bean
    public DataSource mysqlDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setUsername("user name");
        dataSource.setPassword("password");
  
        return dataSource;
    }
}

 

Q38. What is Aspect-Oriented Programming?

Aspect-Oriented programming (AOP) provides a transparent way for the cross-cutting concerns e.g. logging, transaction management, data validation, etc by adding extra behaviour without adding or changing existing classes. It takes out the direct dependency of cross cutting tasks from the classes.

 

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

4 thoughts on “Spring Interview Questions”

Comments are closed.

Scroll to Top