Learn with best explanation

Coding tutorials and solutions

Unleashing Advanced Spring Framework Mastery 2024: Chapter 2's Expert Interview Questions with Answers


Welcome to Chapter 2 of "Unleashing Advanced Spring Framework Mastery 2024." Delve into expert interview questions, exploring ApplicationContext, BeanFactory, bean scopes, and the Spring bean lifecycle. Elevate your Spring proficiency with essential insights for mastering interviews.

What is ApplicationContext and how to use inside spring?

ApplicationContext is the core container for managing beans and providing services to Spring applications. It simplifies bean configuration, dependency injection, and resource management.

This how we should use.

ClassPathXmlApplicationContext context = new 
        ClassPathXmlApplicationContext("applicationContext.xml");
MyService myService = context.getBean("myService", MyService.class);
myService.doSomething();
context.close();

This code shows how to create an ApplicationContext from an XML configuration file, retrieve a bean by name, invoke a method on the bean, and close the ApplicationContext.

What is BeanFactory and how to use inside spring?

BeanFactory is an interface that represents a basic container for managing beans in a Spring application. It provides methods for creating, retrieving, and configuring beans. While ApplicationContextis a more advanced and commonly used container, BeanFactory offers a simpler interface for basic bean management.

Here is example,

BeanFactory factory = new XmlBeanFactory("applicationContext.xml");
MyService myService = factory.getBean("myService", MyService.class);
myService.doSomething();

What is Bean?

Bean: In Spring, a bean is a managed object within the Spring IoC container. It is an instance of a class that is created, managed, and wired together by the Spring framework. Beans are the fundamental building blocks of Spring applications and are typically configured and defined using annotations or XML configuration.

What are Bean scopes?

In Spring Framework, a bean scope defines the lifecycle and the visibility of a bean within the Spring IoC container. Spring Framework provides several built-in bean scopes, each with a specific purpose and behaviour.

The following are the most commonly used bean scopes in Spring Framework:

  • Singleton: (Default) Scopes a single bean definition to a single object instance for each Spring IoC container.
  • Prototype: Scopes a single bean definition to any number of object instances.
  • Request: Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has 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.
  • Session: Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
  • Application: Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
  • Websocket: Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.

What is the Spring bean lifecycle?

In Spring Framework, a bean is an object that is managed by the Spring IoC container. The lifecycle of a bean is the set of events that occur from its creation until its destruction.
The Spring bean lifecycle can be divided into three phases: instantiation, configuration, and destruction.

Instantiation: In this phase, Spring IoC container creates the instance of the bean. Spring Framework supports several ways of instantiating a bean, such as through a constructor, a static factory method, or an instance factory method.

Configuration: In this phase, Spring IoC container configures the newly created bean. This includes performing dependency injection, applying any bean post-processors, and registering any initialization and destruction call-backs.

Destruction: In this phase, Spring IoC container destroys the bean instance. It is the last phase of the Spring bean lifecycle. In addition to these three phases, Spring Framework also provides several callbacks that allow developers to specify custom initialization and destruction logic for a bean.

These callbacks include:

  • @PostConstruct: Invoked after the bean has been constructed and all dependencies have been injected
  • init-method: Specifies a method to be called after the bean has been constructed and all dependencies have been injected
  • destroy-method: Specifies a method to be called just before the bean is destroyed.
  • @PreDestroy: Invoked before the bean is destroyed.

The Spring bean lifecycle is controlled by the Spring IoC container, which creates, configures, and manages the lifecycle of the beans. Developers can take advantage of the bean lifecycle callbacks to add custom initialization and destruction logic to their beans, making it easier to manage the lifecycle of their objects and ensuring that resources are properly.

What is the bean lifecycle in terms of application context?

The bean lifecycle within an application context refers to the various stages a bean goes through from its creation to its destruction. The application context is responsible for managing this lifecycle, ensuring that beans are properly initialized, used, and destroyed at the appropriate times.

Stages of the Bean Lifecycle:

  • Bean Creation: The bean is instantiated, either through constructor injection, setter-based injection, or other mechanisms.
  • Bean Configuration: The bean's properties are set and any necessary initialization callbacks are invoked.
  • Bean Usage: The bean is used by the application, providing its designated functionality.
  • Bean Destruction: The bean is destroyed when it is no longer needed, releasing resources and performing any necessary cleanup tasks.

Application Context's Role in Bean Lifecycle:

  • The application context plays a central role in managing the bean lifecycle, providing various mechanisms to control the creation, configuration, usage, and destruction of beans.
  • Bean Configuration Metadata: The application context stores configuration metadata for beans, defining how they should be created, configured, and managed.
  • Bean Lifecycle Hooks: The application context provides hooks to define custom behavior at various stages of the bean lifecycle, such as initialization and destruction callbacks.
  • Bean Scope Management: The application context manages the scope of beans, determining their visibility and lifetime within the application.
  • Bean Lifecycle Listeners: The application context supports bean lifecycle listeners, allowing components to be notified of changes in the lifecycle of other beans.

Difference Between BeanFactory and ApplicationContext?

Feature BeanFactory ApplicationContext
Functionality Basic bean management Extended bean management with additional services
Bean loading On-demand All at startup (by default)
Supported scopes Singleton, Prototype Singleton, Prototype, Request, Session, etc.
Services Limited Message resources, events, etc.
Use cases Simple applications Complex applications with advanced needs

What is default bean scope in spring?

The default bean scope in Spring is singleton. This means that only one instance of a bean will be created and managed by the Spring container, regardless of how many times it is requested. This scope is useful for beans that are stateless, meaning that they do not maintain any internal state and can be safely shared across different parts of the application.

Below diagram how one instance is created,

How bean is loaded inside spring, can you tell the difference between Lazy loading and Eager loading?

Bean Loading in Spring:

The Spring Framework uses a process called bean instantiation to create beans and make them available to the application. This process involves the following steps:

  • Scanning for beans: The Spring Framework scans the application context for classes that are annotated with Spring annotations such as @Component, @Service, @Repository, and @Controller.
  • Creating bean instances: The Spring Framework creates an instance of each bean class that it finds.
  • Configuring beans: The Spring Framework configures each bean by setting its properties and injecting its dependencies.
  • Initializing beans: The Spring Framework initializes each bean by calling its initialization callbacks.

Lazy Loading vs. Eager Loading? (Important interview Question)

In Spring, beans can be either lazy loaded or eager loaded. Lazy loading means that a bean is not created until it is first requested by the application. Eager loading means that a bean is created when the application starts up.

The default behavior in Spring is to lazy load beans. This can improve the performance of the application because it means that only the beans that are actually needed are created. However, lazy loading can also make the application more difficult to debug because it can be hard to track down which beans have been created and when.

Eager loading can be useful for beans that are needed by the application as soon as it starts up. For example, an application might need to connect to a database as soon as it starts up. In this case, it would make sense to eagerly load the bean that is responsible for connecting to the database.

How to Specify Lazy Loading and Eager Loading?

You can specify whether a bean should be lazy loaded or eagerly loaded using the @Lazy annotation. For example, the following code will create a bean that is lazy loaded:
@Lazy
 @Service

public class MyService 
{
}

The following code will create a bean that is eagerly loaded:

@Service
public class MyEagerService {
}

when to use lazy loading and eager loading?

  • Use lazy loading for beans that are not needed by the application as soon as it starts up.
  • Use eager loading for beans that are needed by the application as soon as it starts up.
  • Use eager loading for beans that have a high startup cost.
  • Use lazy loading for beans that are not frequently used.