Frequently asked Spring Core interview questions and answers

Frequently asked Spring Core interview questions and answers

Spring Framework is one of the most popular Java EE framework for web applications. Nowadays now Spring core and Spring MVC framework are used as a default framework for all new Java application development. With raising popularity on Spring, questions from spring framework have become an integral part of any Java interview. In this post we will see some of the frequently asked Spring Core interview questions and answers.

1. What are the benefits or advantages of spring framework?

This is the first and foremost interview question about spring. This question tests your understanding of the framework and why you use it.

Following are some of the benefits of using 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 using Inversion of Control(IoC) technique. The container provides object’s dependencies instead of creating or looking for dependent objects.
  • Aspect oriented (AOP): Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.
  • Container: Spring IoC container manages the life cycle of Spring Beans and project specific configurations.
  • MVC Framework: Spring’s web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over engineered or less popular web frameworks.
  • Transaction Management: Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example).
  • Exception Handling: Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.
  • Unit testing: Writing unit test cases are easy in Spring framework because our business logic doesn’t have direct dependencies with actual resource implementation classes. We can easily write a test configuration and inject our mock beans for testing purpose.
  • Declarative support: Spring framework provides declarative support for caching, validation, transactions and formatting.
  • Easy to integrate with third party tools and technologies. For example you can also plugin JSF into spring framework.

2. What are the different modules in Spring framework?

The Spring Framework consists of features organized into different modules. These modules are grouped into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation, Messaging, and Test, as shown in the following diagram.

spring framework modules

3. In how many ways, you can configure Spring into your application?

You can configure spring into your application in 3 ways:

  1. XML Based Configuration – where beans are configured with <bean> tag
  2. Annotation-based configuration – here the dependency injection is configured using annotations (@Required, @Autowired, @Qualifier etc). Auto wiring is not turned on in the Spring container by default. You can turn it on by including <context:annotation-config/> in the spring configuration file. We can also use @Component, @Service, @Repository and @Controller annotations with classes to configure them as a spring bean.
  3. Java-based configuration – configuration is done using @Configuration and @Bean annotations

4. What is Dependency Injection?

This is the most frequently asked question in Spring framework. It is important to have a clear understanding of dependency injection in Spring.

The objects in an application have dependencies on each other. Dependency Injection(DI) is a design pattern in which the container(IOC) takes care of injecting dependent objects into another object(whenever it is created). It is a process in which objects define their dependencies i.e. the other objects they work with, the container then injects those dependencies when it creates the bean. This process is fundamentally the inverse, hence it is also known as Inversion of Control (IoC). We can say that dependency injection is an example of Inversion of Control.

Dependency Injection help us to remove the hard-coded dependencies and make our application loosely coupled and easily maintainable.

5. What are the different types of dependency injection?

  • Constructor-based dependency injection: Constructor-based DI is achieved by passing a number of arguments (each representing a dependency on other class) to a class’s constructor. In simple terms, dependencies are given in the form of constructor parameters.
  • Setter-based dependency injection: Setter-based DI is achieved by passing the arguments(dependent objects) to a factory method (setter method) on your beans after invoking a no-argument constructor or no-argument static factory method.

6. Which Dependency Inject would you suggest Constructor-based or setter-based?

It depends on the requirement. It is recommended to use constructor based DI for mandatory dependencies and setter based DI for optional dependencies. You can also use both Constructor-based and Setter-based Dependency Injection.

7. What is Spring IoC container?

The Spring IoC container is responsible for creating the objects, wiring them together(through DI), configuring them, and managing their complete life cycle from creation till destruction. Here is a simple illustration.

spring IOC container

8. What are types of IoC containers?

  • BeanFactory container: This is the simplest container providing basic support for Dependency Injection .The BeanFactory is usually preferred where the resources are limited like mobile devices or applet based applications.
  • Spring ApplicationContext Container: The ApplicationContext container is built on top of the BeanFactory. This container adds more specific functionality such as the ability to resolve textual messages from a properties file (including support for internationalization), Spring AOP integration, EJB integration, remoting, JNDI access, application layer specific context (e.g. WebApplicationContext) for web application and the ability to publish application events to interested event listeners (event propagation).

9. What are the differences between BeanFactory and ApplicationContext?

It allows more than one config files to exist.BeanFactory permits only one configuration file.
Application contexts can publish events to beans that are
registered as listeners.
BeanFactory doesn’t support publishing of events to beans.
It provides support for resolving textual messages, including support for internationalization.BeanFactory doesn’t providesupport for resolving textual messages.
ApplicationContext also provides support for services like
spring AOP integration, EJB integration, remoting, JNDI access and scheduling.
These features too are not supported by Bean Factory.

10. What are the different bean scopes in spring?

  • singleton: Single bean instance will be maintained per Spring IoC container. This is the default scope. This singleton behavior is maintained by bean factory itself.
  • prototype: This scopes a single bean definition to have any number of object instances. The bean instance will be created each and every time a bean is requested.
  • request: With this bean scope, a new bean instance will be created for each HTTP request made by the client. As soon as request completes, bean will be out of scope and garbage collected. Only valid in the context of a web-aware Spring ApplicationContext.
  • session: This scopes ensures one bean instance per HTTP session. The bean instance will be created per user session. Only valid in the context of a web-aware Spring ApplicationContext.
  • global-session: global-session is used only in Portlet applications. When your application works in Portlet container, it is built of some amount of portlets. Each portlet has its own session, but if you want to store variables global for all portlets in your application than you should store them in global-session. In Servlet based applications, this scope doesn’t have any special effect different from session scope.

11. Explain the lifecycle of Spring Bean?

The spring IOC container manages the entire life cycle of spring beans from creation till destruction. Below are the sequence of steps

  • First the spring container loads the bean’s definition from the spring configuration file(XML) and instantiates the bean. Then using the dependency injection, the container populates all of the properties as specified in the bean definition.
  • 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 will be called.
  • If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
  • Now the bean is ready to use by the application.
  • If the bean implements DisposableBean , it will call the destroy() method when the bean is no longer needed(garbage collected).

12. What does @Autowired annotation mean?

The @Autowired annotation indicates that the spring IOC container will inject the dependent bean based on the data type. This annotation can be used on a constructor, field, setter method or config method.

This is the explanation in the spring documentation.

The Spring container can autowire relationships between collaborating beans. You can allow Spring to resolve collaborators (other beans) automatically for your bean by inspecting the contents of the ApplicationContext.

This annotation is similar to @Inject. Note that you cannot autowire primitive data types.

13. Explain different modes of auto wiring in spring?

The autowiring has five modes which can be used to instruct Spring container to use autowiring for dependency injection:

  • no: no autowiring. This is default setting. You should use explicit bean reference for wiring. E.g.
    Here an explicit reference is made via ‘ref’ attribute.
  • byName: Autowiring by property name. 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. E.g.
    Here the customer bean has a property ‘person‘, so Spring will find the “person” bean in the configuration file and wire it automatically. Note that the name of the property is same as the name of a bean (name in this case is same as the id).
  • byType: Autowiring by property datatype. 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. E.g.
    Here the data type of the person object (in customer class) is same as the data type of person bean in the configuration file. So Spring will auto wired it via setter method (setPerson(Person person)).
  • constructor: 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. E.g.
    In the customer class, the data type of the constructor argument is same as the data type of the person bean. So Spring auto wired it via constructor method  (public Customer(Person person)).
  • autodetect: Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType. E.g.

In this case, the auto wire is done using constructor.

14. What does @Qualifier annotation mean?

@Qualifier annotation is used to identify which bean to wire if there are more than one bean (configuration) of the same type when autowiring. To understand it, consider the following bean configuration,

Here there are two beans of type Student.

Now consider the following autowire configuration.

When the above class is run, it will thrown an exception because it can’t find an unique bean of type Student. Hence in this case you can use @Qualifier to mention which bean definition to consider for autowire.

Here is the above example with @Qualifier used.

15. How do you turn on annotation wiring(autowiring) in spring?

Autowiring is not enabled by default in the spring container. So to enable @Autowired, you have to register ‘AutowiredAnnotationBeanPostProcessor‘. This can be done by including <context:annotation-config />  in the spring bean configuration file.

16. What does @Required annotation mean?

@Required annotation marks a method (typically a JavaBean setter method) as being ‘required’: that is, the setter method must be configured to be dependency-injected with a value. In other words, it indicates that the required property must be set while constructing the bean. RequiredAnnotationBeanPostProcessor is a spring bean post processor that checks if all the bean properties with the @Required annotation have been set. It will throw an exception if the affected bean property has not been set.

Consider the following bean class and its bean configuration.

<bean id=”associate” class=”” />

In the above example, if an instance of EmployeeBean is created (or injected) without setting a value for the field ‘designation’, then BeanInitializationException will be thrown.

To avoid this, you can change the bean definition as follow.

Note that you need to register RequiredAnnotationBeanPostProcessor to enable property checking. You can do that by including <context:annotation-config />  in the spring bean configuration file.

17. How do you inject values into collection types List, Set, Map and Properties in a Spring bean?

Spring provides four types of collection configuration elements as follows.

  • <list>: This tag can be used to inject a list of values, allowing duplicates.
  • <set>: This tag can be used to inject a set of values but without any duplicates.
  • <map>: This element can be used to inject a collection of name-value pairs where name and value can be of any type.
  • <props>: This element can be used to inject a collection of name-value pairs where the name and value are both Strings.

Here is an example bean configuration showing the usage of above four elements.


18. What are inner beans in Spring?

Inner beans are the beans that are defined within the scope of another bean. If a bean element (<bean>) is directly embedded in a property or constructor-arg tag (<property> or <constructor-arg>) while wiring beans, then the bean is called an Inner Bean. Inner beans are always anonymous and they are always scoped as prototypes.

Here is an example bean definition.

In the above example, Person is defined as an inner bean.

19. Are singleton beans in spring thread safe?

No, singleton beans are not thread safe.

20. What are the types of the transaction management Spring supports?

Spring supports two types of transaction management:

  • Programmatic transaction management: Transaction is managed with the help of programming. The Spring Framework provides two means of programmatic transaction management:1. Using the TransactionTemplate.
    2. Using a PlatformTransactionManager implementation directly.The Spring team generally recommends the TransactionTemplate for programmatic transaction management.
  • Declarative transaction management: In this you  use annotations (e.g.@Transactional) or XML based configuration to manage the transactions. This means you separate transaction management from the business code. Most Spring Framework users choose declarative transaction management.

21. How is event handling done in Spring and what are the different types of events in spring framework?

Spring’s ApplicationContext provides the functionality to support events. We can create beans that listen for events which are published through the ApplicationContext. Event handling in the ApplicationContext is provided through the ApplicationEvent class and ApplicationListener interface. So if a bean implements the ApplicationListener interface, then every time an ApplicationEvent gets published to the ApplicationContext, the bean is notified. Spring provides the following events:

  1. ContextRefreshedEvent : This event is published when the ApplicationContext is either initialized or refreshed. This can also be triggered using the refresh() method on the ConfigurableApplicationContext interface.
  2. ContextStartedEvent : This event is published when the ApplicationContext is started using the start() method on the ConfigurableApplicationContext interface. You can poll your database or you can start/restart any stopped application after receiving this event.
  3. ContextStoppedEvent : This event is published when the ApplicationContext is stopped using the stop() method on the ConfigurableApplicationContext interface. You can do any resource clean-up activity after receiving this event.
  4. ContextClosedEvent : This event is published when the ApplicationContext is closed using the close() method on the ConfigurableApplicationContext interface. A closed context reaches its end of life; it cannot be refreshed or restarted.
  5. RequestHandledEvent : This is a web-specific event telling all beans that an HTTP request has been serviced.

To listen a context event, a bean should implement the ApplicationListener interface which has just one method onApplicationEvent().

That’s all about some of the frequently asked Spring core interview questions. If you have any doubt, post it in the comments section.

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.
One comment

Add Comment

Required fields are marked *. Your email address will not be published.