Spring IoC Interview Questions List in 2020

This article has an exhaustive list of most frequently asked Spring IoC interview questions.

Current article is part of our series on spring interview questions.

spring ioc interview questions and answers

Spring IOC Interview Questions and Answers

1. What is Inversion of Control (IOC) principle in Spring?

Inversion of control is a programming principle by which ‘control of some aspect’ shifts from client code to some other code, which is typically a generic framework.

In the context of Spring, ‘control of how an object will resolve it’s dependencies’, shifts from program module to Spring Framework.

So now spring framework knows what to do with the objects instead of us creating the object and setting each of it’s dependencies by calling different setters on the object.

You must know that IOC is a generic software engineering principle which is used by many languages to achieve different things. It is not specific to Java or Spring Framework.

2. Is IOC a design pattern?

Yes. IOC is a very well known design pattern/principle which can be implemented in multiple ways.

3. What are the uses / advantages / benefits of IOC in Spring?

Note: This is one of the must know Spring IOC Interview Questions. So, let’s FOCUS.

So, we get:

  1. Loose Coupling.
  2. Better Code testing with Spring IOC.

How?

Well…

As all the concrete object creations and injections are outsourced from the code to the framework, all the concrete dependencies are removed from the classes.

Hence, in case we need to change the dependency from once concrete implementation to other, we do not need to change the code.

Secondly, when there is no any concrete implementation, it’s easy to mock the concrete object and test the code at hand.

Loose coupling vs tight coupling in spring ioc

4. What are different ways to implement Inversion of Control (IOC)?

Although, it is not the comprehensive list but, here are different ways in which we can implement the principle of inversion of control:

  • Using Dependency Injection Pattern
  • Using Service Locator Pattern
  • Using Strategy Design Pattern
  • Using Observer Pattern
  • Using Template Method Design Pattern
  • Using Contextualized Lookup

5. Why is it called IOC in Spring? or Why is IOC named that way?

IOC is a well known design pattern even outside the scope of Java and Spring. Spring just uses the same name.

6. What is Spring IOC container?

Spring IOC container is an object to facilitate inversion of control in Spring. It creates, holds and maintain all the beans throughout it’s life-cycle.

Container is given the metadata in the form of XML or Annotations or Java Code, which tells container about the objects to create and all of their dependencies.

Container then reads this metadata and gets ready with all the objects.

7. How many types of IOC containers are there in spring?

There are two types of IOC containers in general:

  1. BeanFactory Based
  2. ApplicationContext Based

8. What is BeanFactory?

BeanFactory is the parent interface for the container implementations.

BeanFactory provides the core functionalities of container like loading of BeanDefinitions, doing dependency injection and providing APIs to interact with the beans.

ApplicationContext interface also extends BeanFactory interface.

9. Give an example of BeanFactory implementation.

XmlBeanFactory is one of the implementation of BeanFactory.

In this, metadata is provided in the form of XML and after processing that metadata, we can interact with the beans in typical manner.

10. What is Spring ApplicationContext?

According to Spring documentation: “ApplicationContext is a central interface to provide configuration for an application”.

Also, it represents the IOC container. So, all the implementations of ApplicationContext interface is a Spring IOC container.

11. What is the difference between BeanFactory vs ApplicationContext?

BeanFactory is parent interface while ApplicationContext is child interface of BeanFactory.

BeanFactory provides basic interface to communicate with container while ApplicationContext provides more methods on top of that to provide more functionalities like loading file resources, publishing events to the registered listeners.

beanfactory vs applicationcontext

12. How to create ApplicationContext?

Depending upon the environment in which we are creating the application, whether web or stand-alone, Spring provides us multiple implementations of ApplicationContext, by which we can create it’s instances.

Some of them are:

  1. FileSystemXmlApplicationContext: Takes the path of the configuration XML file as an argument and loads the bean definitions.
  2. ClassPathXmlApplicationContext: Takes the XML configuration filename as argument, finds it from the classpath and loads the bean definition.
  3. AnnotationConfigApplicationContext : Loads the bean definitions from the Java classes annotated with @Configuration and provided as argument.
  4. WebXmlApplicationContext: Loads the bean definitions from the XML provided in web application.
  5. AnnotationConfigWebApplicationContext: Works same as AnnotationConfigApplicationContext but in web application environemnt instead of stand-alone.

13. What is Dependency Injection?

Dependency injection is a technique by which a resource or a dependency is provided to the client code.

This is called push mechanism.

Meaning!!?

Let’s understand pull mechanism first.

In a pull mechanism, an object fills it’s dependency by either creating the needed object by itself or locate it via other means like factory method or service locator etc.

While, in push mechanism, an external object or a framework creates the needed object(s) and push (sets the object property) it to the client code where it is needed.

This pushing is called injection. Hence the name Dependency Injection.

In our case, Spring IOC container does this for us.

In this way, client code becomes independent/decoupled from all it’s dependencies.

14. What is the difference between dependency injection (DI) and inversion of control (IOC)?

Answer: IOC defines ‘what’ part of the solution while DI defines ‘how’ part of the solution.

Like with Spring, IOC defines that ‘Dependency Management’ needs to be moved (inverted) from client code to framework.

While, DI is how this dependency management is getting implemented.

If inversion is of some other thing and not of dependency management, then there will be some other technique than DI to achieve that.

15. What are the uses / advantages / benefits of Dependency Injection in Spring?

The advantages are same of Spring IOC:

The advantages discussed above for Spring IOC is discussed under the context of ‘Dependency Injection’ itself.

As we are inverting the control of dependency management, the advantages of Dependency Injection is same as of IOC container and those are:

  1. Loose Coupling and
  2. Better Code Testing.

16. How many types of dependency injection are there in Spring Framework?

This question can be asked in other ways too like:

What types of dependency injection does Spring supports? In how many ways can Dependency Injection be done? or

How can we inject beans in Spring? or

How do we implement DI in Spring framework?

All means same and the answer is:

There are three ways in which we can implement dependency injection with Spring:

  1. Constructor-based dependency injection
  2. Setter-based dependency injection
  3. Method Injection

The major two methods are constructor-based and setter-based, which gets used typically.

Method injection are used only in certain situations like when bean scopes are different.

If you have heard about Interface Injection, Spring does not supports it.

17. Can we inject ‘interface’ in spring IOC?

No. Spring does not support interface injection.

18. What is the difference between constructor injection and setter injection? or Differentiate between constructor injection and setter injection.

In Constructor injection, the dependencies are provided by feeding to the client code constructor whereas..

IN setter injection, the dependencies are provided with the help of setter methods.

In Constructor Injection, framework makes sure that all the dependencies given in the constructor parameter are fulfilled otherwise it will throw exception at run-time. In other words: No partial dependency fulfillment. Whereas..

In setter Injection, if there is no any dependency information in the configuration, there is no any issue. So, no guarantee of the dependency. In other words: Supports partial dependency fulfillment.

Because of the above..

Constructor injection can cause run-time failure if there is any circular dependencies.

Whereas, setter injection is used as one of the solution to prevent circular dependencies.

Constructor based injection precedes setter based injection. Meaning..

If same dependent object reference is injected with two different dependencies: one by constructor and other by setter, then..

first it will injection constructor dependency and then overrides the same with setter dependency.

Because of the above..

In Setter based injection, there is chance that  code can be corrupted by overriding the dependencies.

Whereas in Constructor based injection, code corruption is not a possibility because every-time a constructor based injection will be done, a new object will be formed having new set of dependencies.

19. Which injection is better in spring? or Which is the best way of injecting beans and why?

There is no any better or best way to implement  DI. It all depends on the situation.

For example:

If we want some mandatory behavior where we want to make sure that certain dependencies are always present when creating an object, we should opt for constructor-based injection.

In this way, that object will be in a fully initialized state before getting used. Just make sure that there is no any circular dependency.

For almost all other cases where dependencies can be optional, go for setter-based injection.

This is one of most important Spring IOC Interview Questions. A must to know.

20. Can we have both constructor and setter injection in Spring IOC?

Yes, both constructor and setter injection can be done simultaneously, on a single object.

Some of the dependencies can be fulfilled by constructor and others by setter.

Even, a step further, a single dependency can be fulfilled by both constructor and setter.

In this case, as already stated, first constructor will set the dependency and then setter will set the dependency and hence, will override the constructor’s work.

21. What is method injection?

Method injection is one of the ways to implement dependency injection.

But in this case, instead of injecting some primitive or object reference, a method gets injected.

22. In how many ways can we do method injection?

Method injection can be done in two ways:

  1. Lookup Method Injection
  2. Arbitrary Method Replacement

23. What is lookup method injection?

Lookup method injection is the way by which Spring IOC container overrides method(s) of it’s managed beans(s).

In the background, container creates a subclass of the target object’s class (e.g. A), overrides the injected method and returns this newly built subclass’s (e.g. B extends A) object, whenever you write getBean(“A”).

24. What is arbitrary method replacement?

Arbitrary method replacement is same as lookup method injection with one difference.

In arbitrary method replacement, arbitrary methods of a managed bean can be replaced with newer methods, by the container which is managing that bean.

25. What exception does Spring throws in case of Circular dependency?

ObjectCurrentlyInCreationException

26. Can you inject null and empty string values in spring IOC container?

Yes we can.

27. Can you inject a Java Collection in Spring IOC container?

Yes we can.

Note: From here, we are moving from basic to intermediate Spring IOC Interview Questions.

28. What is a Spring Bean?

Spring Bean is an object which is instantiated, assembled and managed by Spring IOC container.

When we give the metadata configuration to Spring IOC container, it creates and manages the complete life-cycle of all the beans mentioned in the metadata file.

IOC container also fulfills dependency injection requirements of those beans.

29. Explain Spring Bean Life-Cycle.

As IOC container controls all the beans, it provides us different hooks by which we can customize the behavior of the beans.

These hooks/callbacks in the middle of instantiation of bean and destruction of bean, gives us the complete bean life-cycle.

Spring IOC Container does the following in sequence:

  1. Instantiates the Bean: Container first loads the bean definition from the configuration and creates the object from it.
  2. Sets the Properties: In this step, container populates only properties of the object marked for dependency injection.
  3. Sets the BeanName: If the bean implements BeanNameAware interface, container calls setBeanName() method and passes the bean Id to it.
  4. Sets the BeanFactory: If the bean implements BeanFactoryAware interface, container calls setBeanFactory() method and passes the BeanFactory to it.
  5. Pre-Initializes the Bean: There are multiple ways in which we can ask container to run pre-initialization logic. We can use all or any one of them. Here is how it works:
    1. If any BeanPostProcessor is associated with the bean, container first calls postProcessBeforeInitialization() method of all the BeanPostProcessors.
    2. It then calls method annotated with @PostConstruct annotation.
  6. Initializes the Bean: After pre-initialization, container initializes the bean by:
    1. First, calling afterPropertiesSet() method is bean has implemented InitializingBean interface.
    2. And then, custom-init method, if there is any.
  7. After Bean-Initialization: After initialization, container calls postProcessAfterInitialization() method of all the BeanPostProcessor(s) associated with the bean.
  8. At this point, Bean is ‘Ready to use’.
  9. Pre-Destruction: Bean pre-destruction logic can be written in a number of ways and container will call one or all of them depending upon their availability.
    1. First, container calls the method annotated with @PreDestroy annotation.
    2. It then calls destroy() method, if Bean implements DisposableBean interface.
    3. And in last, a custom-destroy method if available.
spring bean lifecycle

30. What is a Spring Configuration file?

Spring configuration file is the XML file which contain the metadata information regarding the project classes.

IOC container uses this configuration file to load bean definitions, create beans and do the dependency injection accordingly.

31. What does a bean definition contains?

Bean definition comprises of all the attributes of <bean> tag. So, all the things starting from it’s id or name to it’s life-cycle details.

Container, loads all this information in BeanDefinition objects.

32. What is the importance of spring bean configuration file?

Spring bean configuration which is holding all the metadata information, and is the input for Spring IOC container.

If we will not provide the configuration file to the container, container won’t do anything. It will be good-for-nothing.

After container reads the configuration file, it creates the beans. With the help of specific ApplicationContext, an application can use the required beans out of available beans in the container.

Note: All the Spring IOC Interview Questions on configuration are kind of mandatory. It is very much expected from the candidates to have answer to these questions.

33. How configuration metadata is provided to the Spring container?

Following are the ways:

  1. XML-Based Configuration
  2. Annotation Based Configuration
  3. Java Based Configuration

34. What is XML-Based Spring Configuration?

In Spring dependency injection, all the details of what objects to create, how to create and other necessary details, are given as configuration metadata.

This metadata can be given by multiple means, popular and primary of which is in the form of XML.

Even the meta-configuration to start the Annotation based configuration, is given in the XML configuration.

Here is an example of XML-based spring configuration (in case you want to detail out to the interviewer):

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/s"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd">
   
 <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close"
        s:driverClassName="com.mysql.jdbc.Driver"
        s:url="jdbc:mysql://localhost:3306/database"
        s:username="root"
        s:password="root" />
</beans>

First, we provide namespaces in the XML configuration file in the <beans> tag.

Then, all the individual bean definitions are given in <bean> tags, which comes under parent <beans> tag.

35. What is Annotation-based Spring Configuration?

In Spring Annotation based configuration, bean definition is given in @ annotated form instead of XML form.

Some examples include: @Autowired, @Qualifier, @PreConstruct, @PostDestroy

As Annotation based config is not the default form given to us by Spring, we need to tell the container in the XML-based configuration (which is the default form) to use the Annotation based configuration.

This is done with the help of <context> tag as follows:

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

<context:annotation-config/>

</beans>

36. What is Java-Based Spring Configuration?

In Spring Java-Based container configuration, we provide the metadata information in the form of Java classes and annotations.

For Example:

@Configuration annotation on a class means that the class can be used as a source of bean definitions and Spring container will register beans mentioned in the class.

@Configuration
public class JavaConfigClass {

}

@Bean annotation on a method means that the method will return an object which will get registered by the IOC container.

So, instead of writing below in the XML:

<beans>
    <bean name="beanName" class="path.to.class.SomeObject"/>
</beans>

We write below in one of the Java class annotated with @Configuration:

@Configuration
public class JavaConfigClass {

    @Bean
    public Someobject methodReturningObject() {
        return new SomeObject();
    }

}

Once we have configuration classes, we register them with AnnotationConfigApplicationContext

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();

//Registering the config classes
   ctx.register(JavaConfigClass.class);
   ctx.refresh();

// Getting the bean from container
   SomeObject myBean = ctx.getBean(SomeObject.class);

37. Can we have multiple configuration file in one project?

Yes, we can. Not only we can, but it is highly recommended.

By having multiple configuration files, it is easier to maintain the files. Also, it makes the project more modular.

We can create multiple files and then link them all in one single file eventually.

We do it by importing them, like below:

<!-- Logistics Module XML: logistics.xml -->
<bean id="logistics" class="path.to.Department" >
    <property name="name" value="Logistics" />
</bean>
<!-- Finance Module XML: finance.xml -->
<bean id="finance" class="path.to.Department" >
    <property name="name" value="Finance" />
</bean>
<!-- Main Project XML -->
<beans>
  <import resource="finance.xml">
  <import resource="logistics.xml">
<!-- Other bean definitions -->
</beans>

38. How to inject a java.util.Properties into a Spring Bean?

This can be done in two steps:

  1. Give the properties path and load the properties file using a property configurer like PropertySourcesPlaceholderConfigurer. By doing this, configurer object will be available to all the beans in the container.
  2. Now, use the expression to get the configurer properties.

Like Below:

<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer>
    <property name="location" value="/path/to/application.properties" />
</bean> 

<bean class="path.to.SomeClass">
    <property name="someClassProperty" value="${propertyKey}"/>
</bean>

39. What are inner beans in Spring IOC container?

Inner beans are nested beans which we inject in the bean’s properties.

Let’s consider the below example:

public class Company
{
  Department department;
}
public class Department
{
  String departmentName;
}

If we want to create ‘Department’ as inner bean for the ‘Company’ bean, we need to specify that in the container metadata, as below:

<bean id="companyBean" class="path.to.companyClass.Company">
    <property name="department">
        <!-- Inner Bean definition START -->
        <bean class="path.to.departmentClass.Department">
            <property name="departmentName" value="Logistics">
        <!-- Inner Bean definition END -->
            </property>
        </bean>
    </property>
</bean>

This can be done via. Constructor injection and Setter injection both.

By nature, inner beans are anonymous, prototype scoped and will be used by ‘single property’.

Note: From here, we are moving from intermediate to advance level Spring IOC Interview Questions.

40. What is bean scope in spring?

In an IOC container, scope defines the boundary of a bean covering it’s complete life-cycle. This gives us the answers to the questions like ‘When will the bean will get created from the bean definition’ or ‘when a bean will get destroyed?’.

For this, container manages the life-cycle of bean differently in different use-cases depending upon different scopes.

41. What are different scopes of Spring Bean?

Spring IOC supports six different types of scopes for a bean. At a time, a bean can choose one out of below given six scopes:

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

42. What Is the Default Bean Scope in Spring IOC?

By default (in case we do not mention the scope attribute in bean definition), container creates bean with singleton scope.

singleton scope in spring ioc container

43. Why default bean scope is Singleton in Spring IOC?

Singleton bean typically means that it will not hold any state (Imagine class level variables).

Typically, it happens to be the case and if something specific is needed then we use specific scoped beans.

So, in an opinionated way, Spring Framework developers found Singleton to be most suitable as default scope.

44. How to Define the Scope of a Bean in Spring IOC?

Spring IoC container allows us to define ‘scope’ of the bean in bean definition as an attribute.

45. Are singleton beans thread-safe in Spring IOC?

The short answer is No.

Detail: By nature, no object is thread-safe by itself. Thread-Safety is the result of how we use that object in our application, how we have implemented the class of that object or what thread safety measures we have taken.

IOC container just provides us plain pre-configured objects according to the bean definition.

So, all the vulnerabilities are present in Singleton bean( or any other type of container bean for that matter), as it is present in objects created by us.

46. How does the Prototype Scope Work in Spring IOC container?

If the scope of a bean is marked as ‘prototype’, then every-time we will call for that bean from IOC container ( by context.getBean(“beanName”)), container will provide a new bean (instance) every-time.

prototype scope in spring ioc container

47. In which scenario, you will use singleton and prototype scope?

Singleton is used in case like configuration classes, utility classes, or classes which does not hold any user specific state.

While prototype is used when we require to introduce entirely new state, a new object to fill every-time.

48. Can we inject a Singleton bean into prototype bean in Spring IOC?

Yes, we can.

So, whenever a new prototype instance gets created, same Singleton bean will be injected.

Note: These Spring IOC interview questions on dependency injection with different scoped beans are the questions, which sometimes makes the interviewer selects or rejects the candidate.

49. Can be inject a Prototype bean into Singleton bean in Spring IOC?

Since, dependencies are injected only once, so Singleton bean will be having the first instance of the prototype scoped bean every-time.

But, we can change this behavior and return a new instance of prototype bean whenever we will call the Singleton bean.

We can do it with the help of method injection techniques.

50. What is stateful and stateless bean in spring IOC container?

In the context of Spring, Stateless beans is the one which does not hold anything specific to the user/anything. For example: Singleton beans.

While the opposite is true for Stateful beans. For example: Prototype Beans.

51. What is bean auto wiring in Spring IOC container?

In every dependency injection, we need to define two things:

  1. The ‘point of injection’ (where to inject) and
  2. which bean to inject at that point of injection.

With bean auto wiring, we just need to define the point of injection. IOC container takes care of finding out which bean to inject.

This automatic selection of beans to inject is obviously determined by one of the modes given by container itself.

Auto-wiring mode is determined by autowire attribute of <bean> tag as below:

<bean id="beanName" class="path.to.BeanClass" autowire="modeName" />  

52. What are different modes of spring bean Auto-wiring?

Different modes by which we can tell container on how to select the beans for auto-wiring are:

  1. no : no mode means ‘No Auto-Wiring’. In this, you will have to explicitly provide the metadata for ‘beans to inject’, as you normally do. This is the default auto-wiring mode so if you do not provide the autowiring attribute, it is considered as no.
  2. byName: byName mode means ‘Auto-Wiring by property name’. In this, container will inject the bean with exact name as property to inject to.
  3. byType : byType mode means ‘Auto-Wiring by bean class type’. In this, container will inject the bean with same type as the property to inject to. This will be possible only when a single implementation of the class is present else exception will be thrown.
  4. constructor: constructor mode means ‘Auto-Wiring by type on constructor’. It is same as byType mode with just one difference. instead of bean properties, it works for bean constructor.
spring ioc container autowiring modes

53. How do you turn on annotation based autowiring in Spring IOC container?

As auto-wiring is not the default way for container to configure itself, we need to explicitly tell the container to it this way.

This explicit telling can be done in two ways:

  1. Add <context:annotation-config/> tag in the configuration file.
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/s"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd">

<context:annotation-config/>

</beans>

2. Add AutowiredAnnotationBeanPostProcessor in the configuration file.

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

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

</beans>

54. What Is the Role of the @Autowired Annotation?

@Autowired annotation is used to specify where exactly we want to inject the bean in automatic way: The ‘point of injection’.

Here is an example of how to do it:

public class ClientCode
{
@Autowired
private String property;

<!-- Getter for 'property' -->
}

@Autowired annotation can be used on constructor, properties and even setter methods.

55. What do you understand by @Qualifier annotation?

Suppose: container identifies two beans which qualifies for the injection, which one will container pick for the @Autowired annotated property.

In such cases of ambiguity, container does not pick any of them and throws a fatal NoSuchBeanDefinitionException saying “No unique bean of type is defined”.

To resolve such issues, spring provides @Qualifier annotation.

Example:

public class Company{
    @Autowired
    private Department department;
    //...
}
public class Department{
    private String name;
    //...
}
<bean id="logistics" class="path.to.Department" >
    <property name="name" value="Logistics" />
</bean>
	
<bean id="finance" class="path.to.Department" >
    <property name="name" value="Finance" />
</bean>

At this point, container will throw exception because it does not know which department to set in the company bean.

To resolve it, we will use @Qualifier annotation as below:

public class Company{
    @Autowired
    @Qualifier("finance")
    private Department department;
    //...
}

56. What do you understand by @Required annotation?

As we know, it is mandatory for container to inject all the constructor properties but, with setters it’s not mandatory.

@Required annotation is used to make the dependency injection mandatory for properties under setter based injection.

In-case, container is unable to do the dependency injection for the @Required annotated setter, it throws BeanInitializationException.

57. What is the difference between auto-wiring and dependency injection?

Give it a thought and it will be as easy as it can.

Auto-wiring is one of the ways in which we can do dependency injection.

We can also say it as a sub-type of Annotation based dependency injection in which the selection of beans to inject is done by container.

Other ways include: XML based and Java based dependency injection.

58. What are the limitations with auto wiring?

Although auto wiring is sometimes very-convenient, but it has got it’s limitations too.

For example:

  1. No support for Primitives: You can not auto-wire primitive values as dependencies.
  2. Not very explicit: For an example: While writing classes, you will have to be sure of other implementations if auto-wiring mode is byType.
  3. Low priority: Dependencies are fulfilled first by auto-wiring and then by XML and Java configuration. So, there are high chances of getting your auto-wired dependencies overridden.

59. Explain Component-Scan process of Spring IOC container.

Component Scan is a way to tell the container ‘where to search for the components to inject‘.

Once we have properly annotated classes, we can tell the container to look for these in two ways:

  1. Using @ComponentScan annotation: Along with @Configuration annotation, if we provide the @ComponentScan annotation without any arguments to it, container will look for the components in the package having @ComponentScan annotation and all of it’s sub-packages. We can also give the list of packages to search in for the components, as arguments in the annotation. For example: @ComponentScan( basePackages= “path.to.package”)
  2. Using XML tag: We can also provide the component scan information in the XML like this: <context:component-scan base-package=” path.to.package”/>

60. What is the difference between <context:annotation-config> and <context:component-scan> ?

While annotation-config will resolve the annotations, component-scan will do the following:

  1. Scanning of the package(s).
  2. Registering the beans.
  3. Resolving the annotations.

61. What is event handling in Spring IOC container?

Event handling is raising events in the container and support managed beans to listen to those events so that they can act on it.

Events are published by ApplicationEventPublisher. These events are composed in the form of ApplicationEvent objects. Beans which implements ApplicationListener interface, will be notified about this event.

Events are part of ApplicationContext and it’s sub-interfaces. It is not the part of BeanFactory.

62. List some of the Spring Framework events.

Here are some of the events:

  1. ContextStartedEvent: This event is published when the ApplicationContext is started using the start() method on the ConfigurableApplicationContext interface.
  2. ContextStoppedEvent: This event is published when the ApplicationContext is stopped using the stop() method on the ConfigurableApplicationContext interface.
  3. ContextRefreshedEvent: This event is published when the ApplicationContext is either initialized or refreshed.
  4. ContextClosedEvent: This event is published when the ApplicationContext is closed using the close() method on the ConfigurableApplicationContext interface.
  5. RequestHandledEvent: This event is raised after completion of each request.

63. Can we create custom events? If yes, then how?

There are 3 steps to do this:

Creating a listener to handle the event, composing the event and publishing it.

64. Why do we use application.properties?

It is typically used to provide the properties which are common to the whole application.

Other than than, it does not hold any special significance.

65. What are the JSR-250 Annotations? Explain them.

Java provides us the list of annotations which we can use.

This provides us the flexibility to not be dependent upon Spring annotations.

We can switch to any framework providing the support for these annotations without impacting our application.

Some of these are: @Resource, @Resources, @PostConstruct, @PreDestroy, @ManagedBean.

And we have finished with our list of interview questions on Spring IOC. This list should be more than enough for anybody.

What to read next?

Next obvious topic you should go though is either Spring MVC Interview Questions or Spring AOP interview questions or Spring Boot interview questions .

Or if you have something else in mind, checkout our series on Spring Interview questions and pick the topic according to your profile.

Good Luck!!

Leave a Comment