11 Essential Spring Interview Questions *

Toptal sourced essential questions that the best Spring developers and engineers can answer. Driven from our community, we encourage experts to submit questions and offer feedback.

Hire a Top Spring Developer Now
Toptal logois an exclusive network of the top freelance software developers, designers, finance experts, product managers, and project managers in the world. Top companies hire Toptal freelancers for their most important projects.

Interview Questions

1.

What is a Spring Bean Factory? What are some of the implementations available?

View answer

A BeanFactory is the actual container which instantiates, configures and manages all Spring beans together with their dependencies. Bean factories are represented by the interface org.springframework.beans.factory.BeanFactory and its sub-interfaces including:

  • ApplicationContext
  • WebApplicationContext
  • AutowireCapableBeanFactory

All of which are implemented with:

  • AnnotationConfigWebApplicationContext
  • XmlWebApplicationContext
  • ClassPathXmlApplicationContext
  • FileSystemXmlApplicationContext

It’s important to note that implementations can correspond to multiple interfaces.

2.

Which steps of beans lifecycle can be overridden or controlled?

View answer

The init() method is called when the bean is loaded to the container via the init-method attribute in the xml configuration with the @PostConstruct annotation. The destroy() method is called when the bean is unloaded from the container, through the destroy-method attribute in the xml configuration with the @PreDestroy annotation. If a bean is a prototype-scoped, the client code must clean up objects and release expensive resources that the prototype beans are holding. To get the Spring container to release resources held by prototype-scoped beans, try using a custom BeanPostProcessor, which holds a reference to beans that need to be cleaned up.

A developer can implement various interfaces to invoke specific behavior during a bean’s life cycle, such as InitializingBean and DisposableBean, as well as BeanNameAware, BeanFactoryAware and ApplicationContextAware.

3.

What bean scopes are supported by Spring and what do they mean? Which is used by default?

View answer

The Spring Framework supports following scopes:

  • singleton (used by default): This means a single instance per Spring container; not thread-safe
  • prototype: This means any number of object instances.
  • request: This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.
  • session: This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
  • global-session: This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.

Apply to Join Toptal's Development Network

and enjoy reliable, steady, remote Freelance Spring Developer Jobs

Apply as a Freelancer
4.

What is dependency injection (DI)? What are the types of DI?

View answer

Dependency injection is the concept where you do not create your objects but describe how they should be created, and then expect pre-created objects to be passed in. Likewise, you don’t directly connect your components together but describe which components are needed with either a configuration file or an annotation. The Spring container is responsible for the rest.

DI can be either constructor based or setter based. Constructor based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other classes. Setter based dependency injection is accomplished when the container calls setter methods on a bean after instantiating it.

5.

Describe the Spring bean lifecycle.

View answer

The lifecycle of a Spring bean consists the following steps:

  1. Instantiation
  2. Properties population
  3. Call of setBeanName() method of BeanNameAware
  4. Call of setBeanFactory() method of BeanFactoryAware
  5. Call of setApplicationContext() of ApplicationContextAware
  6. Pre-initialization with BeanPostProcessor
  7. Call of afterPropertiesSet() method of InitializingBean
  8. Custom init method
  9. Post-initialization with BeanPostProcessor
  10. Bean is ready to use
  11. Call of destroy() method of DisposableBean
  12. Custom destroy method

Numbers 11-12 are actual for all scopes except prototype, since Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, and otherwise assembles a prototype object and hands it to the client with no further record of that prototype instance.

6.

What is a Spring Application Context? What are some example usages of one?

View answer

An ApplicationContext is an interface extending BeanFactory’s functionality. In addition to the BeanFactory’s methods, ApplicationContext provides the ability to:

  • Load file resources by extending the ResourcePatternResolver interface
  • Publish events to registered listeners (via the ApplicationEventPublisher interface)
  • Resolve messages supporting internationalization (with the MessageSource interface).

It’s read-only while the application is running.

The easiest way to create an ApplicationContent instance is:

ApplicationContext ctx = new FileSystemXmlApplicationContext("application.xml");

Loading resources is done with:

ctx.getResources(String locationPattern);
ctx.getResource(String location);

Publishing events is as simple as:

ctx.publishEvent(ApplicationEvent event);
ctx.publishEvent(Object event);

Internationalization support messages can be done by:

ctx.getMessage(String code, Object[] args, String defaultMessage, Locale locale);
ctx.getMessage(String code, Object[] args, Locale locale);
ctx.getMessage(MessageSourceResolvable resolvable, Locale locale);
7.

In the context of Spring, what is a “stereotype”? What are the existing stereotypes and what is the difference between them?

View answer

Stereotype is a class-level annotation denoting the roles of types or methods in the overall architecture (at a conceptual level, rather than implementation). In Spring, these annotations live in the package org.springframework.stereotype.

Currently, this package has the following annotations:

  • @Component indicates that an annotated class is a “component”. Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.
  • @Controller indicates that an annotated class is a “Controller” (e.g. a web controller).
  • @Repository indicates that an annotated class is a “Repository”, originally defined by Domain-Driven Design (Evans, 2003) as “a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects”.
  • @Service indicates that an annotated class is a “Service”, originally defined by Domain-Driven Design (Evans, 2003) as “an operation offered as an interface that stands alone in the model, with no encapsulated state.” May also indicate that a class is a Business Service Facade (in the Core J2EE patterns sense) or something similar.

These different types primarily allow a developer easily distinguish the purpose of the annotated classes. Starting with Spring 2.5, @Controller, @Repository and @Service serve as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.

8.

How do you load and inject properties into a Spring Bean?

View answer

Let’s say we have a custom.properties file that defines a database connection timeout property called connection.timeout. To load this property into a Spring context, we need to define a propertyConfigurer bean:

<bean id="propertyConfigurer" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="location" value="custom.properties" />
</bean>

After that we can use Spring Expression Language to inject properties into other beans:

<bean class="com.toptal.spring.ConnectionFactory">
    <property name="timeout" value="${connection.timeout}"/>
</bean>

The same is available in the annotation based configuration, like so:

@Value("${connection.timeout}") 
private int timeout;
9.

What are the different ways to configure a class as Spring Bean?

View answer

There are multiple ways to configure Spring Bean: XML configuration, Java based configuration and annotation based configuration.

XML configuration
<bean id="myBean" class="com.toptal.spring.MyBean"/>
Java Based Configuration

Any object can be put into Spring Context and be reused later as a usual bean.

ConfigurableApplicationContext context;
context.getBeanFactory().registerSingleton(name, obj);
Annotation Based Configuration

A Spring Bean can be configured with the @Bean annotation, which is used together with @Configuration classes.

@Configuration
public class MyConfiguration {

	@Bean
	public MyService getService(){
		return new MyService();
	}
}

The annotations @Component, @Service, @Repository and @Controller can also be used with classes to configure them as Spring Beans. In this case, the base package location has to be provided to scan for these classes, like so:

<context:component-scan base-package="com.toptal.spring" />
10.

What is Bean wiring? How does autowiring work?

View answer

Bean wiring is the process of injection Spring Bean dependencies while initializing. It’s usually best practice to wire all dependencies explicitly, (with XML configuration, for example), but Spring also supports autowiring with the @Autowired annotation. To enable this annotation we need to put the context:annotation-config element into the Spring configuration file. To avoid conflicts in bean mapping while autowiring, the bean name has to be provided with the @Qualifier annotation.

There are different ways to autowire a Spring Bean:

  • byName - to use this type setter method for dependency injection, the variable name should be the same in both the class where the dependency will be injected and in the Spring configuration file.
  • byType - in order for this to function, there should be only one bean configured for that specific class.
  • Via constructor - similar to byType, but type is applied to constructor arguments.
  • Via autodetect - now obsolete, used in Spring 3.0 and earlier, this was used to autowire by constructor or byType.
11.

Which dependency injection method is better: Constructor-based or setter-based?

View answer

You can use both Constructor-based and Setter-based Dependency Injection. The best solution is using constructor arguments for mandatory dependencies and setters for optional dependencies.

There is more to interviewing than tricky technical questions, so these are intended merely as a guide. Not every “A” candidate worth hiring will be able to answer them all, nor does answering them all guarantee an “A” candidate. At the end of the day, hiring remains an art, a science — and a lot of work.

Why Toptal

Tired of interviewing candidates? Not sure what to ask to get you a top hire?

Let Toptal find the best people for you.

Hire a Top Spring Developer Now

Our Exclusive Network of Spring Developers

Looking to land a job as a Spring Developer?

Let Toptal find the right job for you.

Apply as a Spring Developer

Job Opportunities From Our Network

Submit an interview question

Submitted questions and answers are subject to review and editing, and may or may not be selected for posting, at the sole discretion of Toptal, LLC.

* All fields are required

Looking for Spring Developers?

Looking for Spring Developers? Check out Toptal’s Spring developers.

Slava Medvediev

Freelance Spring Developer
PortugalToptal Member Since October 21, 2019

Slava is a certified Java programmer with 12+ years of experience in the IT industry. He started his IT career as a test engineer and has since worked as a test lead, Java developer, lead developer, and tech lead. He has strong engineering and communication skills in addition to rich experience in server-side technologies, frameworks, and development tools.

Show More

Joe Cavazos

Freelance Spring Developer
United StatesToptal Member Since June 19, 2016

Joe is a principal Java developer and architect with over 14 years of experience developing enterprise and small-scale applications. He has experience at all stages of the SDLC and is well-versed in relational databases, application servers, REST APIs, and testing.

Show More

Nemanja Stefanovic

Freelance Spring Developer
SerbiaToptal Member Since September 10, 2019

Nemanja is a motivated software engineer with excellent technical and problem-solving skills. Recently, he's worked on different projects in the Office natural language team at Microsoft—across all product aspects from the design, coding, testing, and validation of back-end service APIs. Nemanja is interested in client/server apps and specializes in .NET technologies and also works with the Java technology stack.

Show More

Toptal Connects the Top 3% of Freelance Talent All Over The World.

Join the Toptal community.

Learn more