Learn with best explanation

Coding tutorials and solutions

Spring Framework Success Secrets 2024: Expert Tips, Premium Insights, and Chapter 1's Must-Know Interview Questions


Welcome to comprehensive and premium frequently asked interview questions series. The series is composed of after discussing with about 15 senior java spring boot developers. In this series I have also added the collection of interview questions which were asked from me during the interviews. Till date I have given interviews in 80 companies national and multinational.

Knowing Spring Framework before jumping into Spring Boot is like building a strong base before constructing a house. Spring Framework teaches you the essential concepts and inner workings of how things operate in Java development, like handling dependencies and organizing code. This knowledge helps you understand why Spring Boot, which is like a faster and more efficient version of Spring, does things the way it does. It's like learning the basics before using a time-saving tool that's built on those basics. So, by mastering Spring first, you'll have a better grip on Spring Boot and make smarter choices when creating modern applications. Let’s dive into the Spring framework interview questions,

What is Spring Framework?

The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications - on any kind of deployment platform. A key element of Spring is infrastructural support at the application level: Spring focuses on the "plumbing" of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.

What is Inversion of control?

In traditional programming, you would have to manually create and manage all the objects that your application needs. This can be a complex and error-prone process. This diagram shows how IOC looks like,

Don't let object to create itself the instances of the object that it references, the job is delegated to container (Assembler in the picture)

The Spring Framework's IoC container simplifies this process by taking over the responsibility of creating and managing objects. You simply tell Spring what objects you need, and it will create them for you and provide them to your code. This is called dependency injection. Dependency injection makes your code more modular and easier to maintain. It also reduces the risk of errors, because you no longer have to worry about creating objects correctly. IoC is also known as dependency injection (DI). It is a process whereby objects define their dependencies (that is, the other objects they work with) only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse (hence the name, Inversion of Control) of the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes.

What is Spring IOC Container?

The org.springframework.context.ApplicationContext interface represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the beans. The container gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata. The configuration metadata is represented in XML, Java annotations, or Java code. It lets you express the objects that compose your application and the rich inter-dependencies between those objects.

In How many ways we can define the configuration in spring?

We can do that in two ways:
1. XML based config: It can be useful to have bean definitions span multiple XML files. Often, each individual XML configuration file represents a logical layer or module in your architecture.
2. Java-based configuration: define beans external to your application classes by using Java rather than XML files. To use these features, see the @Configuration, @Bean, @Import, and @DependsOn annotations.

What is Dependency injection?

Dependency injection (DI) is a process whereby objects define their dependencies (that is, the other objects with which they work) only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse (hence the name, Inversion of Control) of the bean itself controlling the instantiation or location of its dependencies on its own by using direct construction of classes or the Service Locator pattern.
Code is cleaner with the DI principle, and decoupling is more effective when objects are provided with their dependencies. The object does not look up its dependencies and does not know the location or class of the dependencies. As a result, your classes become easier to test, particularly when the dependencies are on interfaces or abstract base classes, which allow for stub or mock implementations to be used in unit tests. DI exists in two major variants: Constructor-based dependency injection and Setter-based dependency injection. Typically, Diagram Looks like this,

Difference between Inversion of Control and Dependency Injection?

Feature Inversion of Control (IoC) Dependency Injection (DI)
Concept Design principle Implementation pattern
Focus Overall control flow of the application Providing dependencies to objects
Goal Decouple objects and increase flexibility Improve maintainability and testability
Mechanism External entity (e.g., framework) controls object creation and dependencies Inject dependencies into objects through constructors, setters, or method arguments
Relationship IoC is the broader concept; DI is a specific way to implement IoC DI is a tool used to achieve IoC principles
Benefits Increased flexibility, testability, and maintainability Improved code organization, reduced coupling, and easier testing

What are the types of dependency injection and what benefit we are getting using that?

Dependency injection (DI) is a design pattern that allows objects to be supplied with their dependencies, rather than having to create them themselves. There are several types of dependency injection, each with its own benefits:

  • Constructor injection: In this type of injection, the dependencies are passed to the constructor of the class when it is instantiated. This ensures that the class always has the required dependencies and can be useful for enforcing class invariants.

The following example shows a class that can only be dependency-injected with constructor injection:

public class SimpleMovieLister {
    // the SimpleMovieLister has a dependency on a MovieFinder
    private final MovieFinder movieFinder;
    // a constructor so that the Spring container can inject a MovieFinder
    public SimpleMovieLister(MovieFinder movieFinder) {
        this.movieFinder = movieFinder;
    }
    // business logic that actually uses the injected MovieFinder is omitted...
}
  • Setter injection: In this type of injection, the dependencies are passed to setter methods of the class after it has been instantiated. This allows the class to be reused in different contexts, as the dependencies can be changed at runtime.

The following example shows a class that can only be dependency-injected with setter injection:

public class SimpleMovieLister {
    // the SimpleMovieLister has a dependency on the MovieFinder
    private MovieFinder movieFinder;
    // a setter method so that the Spring container can inject a
    //MovieFinder
    public void setMovieFinder(MovieFinder movieFinder) {
        this.movieFinder = movieFinder;
    }
    // business logic that actually uses the injected MovieFinder is omitted...
}

Which one is better Constructor-based or setter-based DI?

Since you can mix constructor-based and setter-based DI, it is a good rule of thumb to use constructors for mandatory dependencies and setter methods or configuration methods for optional dependencies. Note that use of the @Autowired annotation on a setter method can be used to make the property be a required dependency; however, constructor injection with programmatic validation of arguments is preferable. The Spring team generally advocates constructor injection, as it lets you implement application components as immutable objects and ensures that required dependencies are not null. Furthermore, constructor-injected components are always returned to the client (calling) code in a fully initialized state.

What is Method Injection?

Method Injection is a design pattern commonly used in Spring and other frameworks to inject dependencies into objects. Unlike field injection or constructor injection, which inject dependencies directly into fields or constructors, method injection injects dependencies into specific method arguments.

How inversion of control works inside the container?

Inversion of Control (IoC) is a design pattern that allows control to be transferred from the application code to an external container. In the context of a Java application, this container is often referred to as an IoC container or a dependency injection (DI) container. IoC containers are responsible for creating and managing objects, and they do this by relying on a set of configuration rules that define how objects are created and wired together.

Here's how IoC works inside an IoC container:

  • Configuration: In order to use an IoC container, you need to configure it with a set of rules that define how objects should be created and wired together. This configuration is typically done using XML or Java annotations.
  • Object creation: When your application requests an object from the container, the container uses the configuration rules to create a new instance of the requested object.
  • Dependency injection: The container injects any required dependencies into the newly created object. These dependencies are typically defined in the configuration rules. Object lifecycle management: The container manages the lifecycle of the objects it creates. This means that it's responsible for creating, initializing, and destroying objects as required by the application.
  • Inversion of control: By relying on the container to create and manage objects, the application code no longer has direct control over the object creation process. Instead, the container takes on this responsibility, and the application code simply requests the objects it needs from the container.

What are Spring MVC, Spring AOP and Spring Core modules?

Reason to ask this question is, these three modules are very important while developing the spring-based application. Spring MVC, Spring AOP, and Spring Core are three essential modules of the Spring Framework that play crucial roles in building robust and scalable Java applications.

Spring MVC (Model-View-Controller)

Spring MVC is a web framework that implements the Model-View-Controller (MVC) architecture, a popular pattern for separating application logic, user interface presentation, and data management. It provides a layered approach to handling web requests, making it easier to develop maintainable and testable web applications.

Key features of Spring MVC include:

  • Dispatcher Servlet: Centralizes request handling and dispatching to appropriate controllers.
  • Controller classes: Handle user requests by processing data, interacting with the model, and selecting appropriate views.
  • View technologies: Supports various templating engines like JSP, FreeMarker, Thymeleaf, and Velocity to render dynamic content.

Spring AOP (Aspect-Oriented Programming)

Spring AOP provides an implementation of aspect-oriented programming (AOP), a technique for modularizing cross-cutting concerns like logging, security, and transaction management. It allows developers to encapsulate these concerns as aspects and apply them to specific points within the application's execution flow.

Key features of Spring AOP include:

  • Aspect declaration: Defines aspects, specifying the cross-cutting concern and the pointcuts where it should be applied.
  • Aspect weaving: Integrates aspects into the application's execution flow, applying the aspect's behavior at specific join points.
  • Aspect execution: Handles the invocation of aspect advice, which defines the actions to be taken at the join points.

Spring Core

Spring Core is the foundation of the Spring Framework, providing essential services like dependency injection, bean lifecycle management, and resource management. It's responsible for creating, configuring, and managing objects throughout the application.

Key features of Spring Core include:

  • Dependency injection: Automatically supplies objects with their dependencies, reducing code complexity and improving modularity.
  • Bean lifecycle management: Handles the creation, initialization, destruction, and scope of objects within the Spring application context.
  • Resource management: Manages resources like database connections, files, and messaging queues, simplifying resource acquisition and release.

How Component Scanning(@ComponentScan) Works?

  • Annotation Discovery: The Spring Framework uses annotation-based configuration to identify Spring beans. It scans the specified packages and sub -packages for classes annotated with @Component, @Service, @Repository, @Controller, or other stereotype annotations that indicate a bean's role in the application.
  • Bean Creation and Registration: Upon discovering annotated classes, the Spring Framework creates instances of those classes and registers them as Spring beans in the application context. The application context maintains a registry of all managed beans, making them accessible for dependency injection.
  • Bean Configuration: The Spring Framework applies default configuration rules to the registered beans. These rules include dependency injection, bean lifecycle management, and resource management. Developers can further customize bean configuration using annotations, XML configuration files, or programmatic configuration.

Example Configuration Class:

@Configuration
@ComponentScan("com.example.springapp")
public class AppConfig {
}

This configuration class defines two annotations:

  • @Configuration: Marks this class as a source of bean definitions for Spring.
  • @ComponentScan: Specifies the base package for component scanning. Spring will scan this package and its sub-packages for classes annotated with @Component, @Service, @Repository, or @Controller, and register them as Spring beans.