Summary of Spring’s classic interview questions (the most complete list in history)

1. Basic Concepts

1.1. What are the main features of the different versions of Spring Framework?

Version Feature
Spring 2.5 Released in 2007. This is the first version to support annotations.
Spring 3.0 Published in 2009. It takes full advantage of the improvements in Java5 and provides support for JEE6.
Spring 4.0 Published in 2013. This is the first version to fully support JAVA8.

1.2. What is Spring Framework?

Spring is an open source application framework designed to reduce the complexity of application development.
It is lightweight and loosely coupled.
It has a layered architecture that allows users to select components, while also providing a cohesive framework for J2EE application development.
It can integrate other frameworks, such as Structs, Hibernate, EJB, etc., so it is also called the framework of the framework.

1.3. List the advantages of the Spring Framework.

Due to the layered architecture of Spring Frameworks, users can freely choose the components they need.
Spring Framework supports POJO (Plain Old Java Object) programming for continuous integration and testability. JDBC is simplified
thanks to [Dependency Injection and Inversion of Control.]
It is open source and free.

1.4. What are the different features of the Spring Framework?

Lightweight – Spring is lightweight in terms of code size and transparency.
[IOC] – Inversion of Control
[AOP] – Aspect Oriented Programming can separate application business logic and system services to achieve high cohesion.
Container – Spring is responsible for creating and managing the lifecycle and configuration of objects (Beans).
[MVC] – provides a high degree of configurability for web applications, and the integration of other frameworks is also very convenient.
Transaction Management – Provides a generic abstraction layer for transaction management. Spring’s transaction support is also available in container-less environments.
JDBC exceptions – Spring’s JDBC abstraction layer provides an exception hierarchy that simplifies error handling strategies.

1.5. How many modules are there in the Spring Framework and what are they?

Spring Core Container – This layer is basically the core of the Spring Framework. It contains the following modules:

  • Spring Core
  • Spring Bean
  • SpEL (Spring Expression Language)
  • Spring Context

Data Access/Integration – This layer provides support for interacting with the database. It contains the following modules:

  • JDBC (Java DataBase Connectivity)
  • ORM (Object Relational Mapping)
  • OXM (Object XML Mappers)
  • JMS (Java Messaging Service)
  • Transaction

Web – This layer provides support for creating web applications. It contains the following modules:

  • Web
  • Web – Servlet
  • Web – Socket
  • Web – Portlet

AOP – This layer supports Aspect Oriented Programming
Instrumentation – This layer provides support for class detection and class loader implementation.
Test – This layer provides support for testing with JUnit and TestNG.
Several miscellaneous modules:

  • Messaging – This module provides support for STOMP. It also supports the annotation programming model for routing and processing
    STOMP messages from WebSocket clients
  • Aspects – This module provides support for integration with AspectJ.

1.6. What is a Spring configuration file?

Spring configuration files are XML files. This file mainly contains class information. It describes how these classes are configured and introduced into each other. However, XML configuration files are verbose and much cleaner. It becomes very difficult to manage in a large project if it is not planned and written correctly.

1.7. What are the different components of a Spring application?

Spring applications generally have the following components:
Interface – defines functionality.
Bean class – It contains properties, setter and getter methods, functions, etc.
Spring Aspect Oriented Programming (AOP) – Provides the functionality of Aspect Oriented Programming.
Bean Configuration File – Contains information about classes and how to configure them.
User program – it uses the interface.

1.8. What are the ways to use Spring?

Use Spring in the following ways:

  • As a full-fledged Spring web application.
  • As a third-party web framework, use the Spring Frameworks middle tier.
  • For remote use.
  • As an Enterprise Java Bean, it can wrap existing POJOs (Plain Old Java Objects).

2. Dependency Injection (Ioc)

2.1. What is the Spring IOC container?

At the heart of the Spring Framework is the Spring container. Containers create objects, assemble them together, configure them, and manage their complete lifecycle. The Spring container uses dependency injection to manage the components that make up an application.
The container receives instructions for object instantiation, configuration, and assembly by reading the provided configuration metadata. This metadata can be provided via XML, Java annotations or Java code.

2.2. What is Dependency Injection?

In dependency injection, you don’t have to create objects, but you must describe how to create them. Instead of connecting components and services together directly in code, you describe which components need which services in a configuration file. They are assembled together by the IoC container.

2.3. In how many ways can dependency injection be done?

Generally, dependency injection can be done in three ways, namely:

  • Constructor injection
  • setter injection
  • Interface Injection
    In the Spring Framework, only constructor and setter injection is used.

2.4. Distinguish between constructor injection and setter injection.

Constructor injection setter injection
no partial injection with partial injection
Constructor injection setter injection
Does not override setter properties Overrides the setter property
Any modification will create a new instance Arbitrary modification does not create a new instance
Suitable for setting many properties Good for setting few properties

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

  • BeanFactory – BeanFactory is like a factory class containing a collection of beans. It instantiates the bean when requested by the client.
  • ApplicationContext – The ApplicationContext interface extends the BeanFactory interface. It
    provides some additional functionality on top of BeanFactory.

2.6. Distinguish between BeanFactory and ApplicationContext.

BeanFactory ApplicationContext
it uses lazy loading it uses instant loading
It uses syntax to explicitly provide resource objects It creates and manages resource objects by itself
Internationalization is not supported Support internationalization
Dependency-based annotations are not supported Support for dependency-based annotations

2.7. List some of the benefits of IoC.

Some of the benefits of IoC are:

  • It will minimize the amount of code in the application.
  • It will make your application easier to test because it doesn’t require any singleton or JNDI lookup mechanism in unit test cases.
  • It promotes loose coupling with minimal impact and minimal intrusive mechanisms.
  • It supports instant instantiation and lazy loading of services.

2.8. Implementation mechanism of Spring IoC.

The implementation principle of IoC in Spring is the factory mode plus reflection mechanism.
Example:

interface Fruit {
     public abstract void eat();
}
class Apple implements Fruit {
    public void eat(){
        System.out.println("Apple");
    }
}
class  Orange  implements  Fruit  {
     public  void  eat () {
        System.out.println("Orange");
    }
}
class Factory {
    public static Fruit getInstance(String ClassName) {
        Fruit f=null;
        try {
            f=(Fruit)Class.forName(ClassName).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return f;
    }
}
class Client {
    public static void main(String[] a) {
        Fruit f=Factory.getInstance("io.github.dunwu.spring.Apple");
        if(f!=null){
            f.eat();
        }
    }
}

3、Beans

3.1. What are spring beans?

  • They are the objects that make up the backbone of the user’s application.
  • Beans are managed by the Spring IoC container.
  • They are instantiated, configured, wired and managed by the Spring IoC container.
  • Beans are created based on configuration metadata provided to the container by the user.

3.2. What configuration methods does spring provide?

  • xml based configuration

The dependencies and services required by the bean are specified in an XML-formatted configuration file. These configuration files typically contain many bean definitions and application-specific configuration options. They usually start with a bean tag. E.g:

<bean id="studentbean" class="org.edureka.firstSpring.StudentBean">
 <property ></property>
</bean>

  • Annotation-based configuration

Instead of using XML to describe bean assembly, you can configure a bean as the component class itself by using annotations on the relevant class, method, or field declarations. By default, annotation assembly is not turned on in the Spring container. Therefore, you need to enable it in the Spring configuration file before using it. E.g:

<beans>
<context:annotation-config/>
<!-- bean definitions go here -->
</beans>

  • Configuration based on Java API

Spring’s Java configuration is achieved through the use of @Bean and @Configuration.

  1. The @Bean annotation plays the same role as an element.
  2. @Configuration classes allow inter-bean dependencies to be defined by simply calling other @Bean methods in the same class.

E.g:

@Configuration
public class StudentConfig {
    @Bean
    public StudentBean myStudent() {
        return new StudentBean();
    }
}

3.3. Does spring support centralized bean scope?

Spring beans support 5 scopes:

  • Singleton – There is only one singleton per Spring IoC container.
  • Prototype – A new instance is produced on every request.
  • Request – A new instance is generated for each HTTP request, and the bean is only valid within the current HTTP request.
  • Session – Each HTTP request will generate a new bean, and the bean is only valid within the current HTTP session.
  • Global-session – Similar to the standard HTTP Session scope, but it only makes sense in portlet-based web applications. The Portlet specification defines the concept of a global Session, which is shared by all the various portlets that make up a portlet web application. Beans defined in the global session scope are scoped to the lifetime of the global portlet Session. If you use the global session scope to identify the bean in the web, then the web will automatically be used as the session type.

The last three are only available if the user is using a web-enabled ApplicationContext. More spring content

3.4. What is the lifecycle of a spring bean container?

The life cycle flow of the spring bean container is as follows:

  1. The Spring container instantiates beans according to the bean definitions in the configuration
  2. Spring uses dependency injection to populate all properties, as defined in the bean configuration.
  3. If the bean implements the BeanNameAware interface, the factory calls setBeanName() by passing the bean’s ID.
  4. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory() by passing an instance of itself.
  5. The preProcessBeforeInitialization() method is called if there are any BeanPostProcessors associated with the bean .

  6. If an init method (the init-method attribute of ) is specified for the bean, it will be called.
  7. Finally, if there are any BeanPostProcessors associated with the bean, the
    postProcessAfterInitialization() method will be called.
  8. If the bean implements the DisposableBean interface, destroy() will be called when the spring container shuts down.
  9. If the destroy method is specified for the bean (the destroy-method attribute of ), it will be called.

3.5. What are spring internal beans?

A bean can only be declared as an inner bean when the bean is used as a property of another bean. To define beans, Spring’s XML-based configuration metadata provides the use of elements in or . Inner beans are always anonymous, they are always used as prototypes.
For example, suppose we have a Student class that references the Person class. Here we will just create an instance of the Person class and use it in Student.
Student.java

public class Student {
    private Person person;
    //Setters and Getters
}
public class Person {
    private String name;
    private String address;
    //Setters and Getters
}

bean.xml

<bean id=“StudentBean" class="com.edureka.Student">
    <property >
        <!--This is inner bean -->
        <bean class="com.edureka.Person">
            <property  value=“Scott"></property>
            <property  value=“Bangalore"></property>
        </bean>
    </property>
</bean>

3.6. What is spring assembly

When beans are grouped together in the Spring container, it is called wiring or bean wiring. The Spring container needs to know what beans are needed and how the container should use dependency injection to bind the beans together and wire the beans.

3.7. What are the methods of autowiring?

The Spring container is able to autowire beans. That is, Spring can automatically resolve bean collaborators by inspecting the contents of the BeanFactory.
Different modes of autowiring:

  • no – This is the default setting, meaning no autowiring. Wiring should be done using an explicit bean reference.
  • byName – It injects object dependencies based on the bean’s name. It matches and assembles beans whose properties are defined by the same name in the XML file.
  • byType – it injects object dependencies based on type. If the property’s type matches a bean name in the XML file, the property is matched and wired.
  • Constructor − It injects dependencies by calling the constructor of the class. It has tons of parameters.
  • autodetect – First the container tries to wire via the constructor using autowire, if not, it tries to autowire via byType.

3.8. What are the limitations of autowiring?

  • Possibility to override – you can always specify dependencies with and set, which will override autowiring.
  • Basic Metadata Types – Simple properties such as primitives, strings and classes cannot be autowired.
  • Confusing nature – always prefer to use explicit assembly as auto assembly is less precise.

4. Notes

4.1. What important Spring annotations have you used?

  • @Controller – Used for controller classes in Spring MVC projects.
  • @Service – for service classes.
  • @RequestMapping – Used to configure URI mapping in controller handler methods.
  • @ResponseBody – Used to send an Object as a response, typically XML or JSON data as a response.
  • @PathVariable – Used to map dynamic values ​​from URIs to handler method parameters.
  • @Autowired – for autowired dependencies in spring beans.
  • @Qualifier – use the @Autowired annotation to avoid confusion when there are multiple instances of the bean type.
  • @Scope – The scope used to configure the spring bean.
  • @Configuration, @ComponentScan and @Bean – for java based configuration.
  • @Aspect, @Before, @After, @Around, @Pointcut – for Aspect Programming (AOP).

4.2. How to start annotation assembly in spring?

By default, annotation assembly is not turned on in the Spring container. Therefore, to use annotation-based wiring, we must enable it in the Spring configuration file by configuring the element.

4.3. What is the difference between @Component, @Controller, @Repository, @Service?

  • @Component: This marks the java class as a bean. It is a generic stereotype for any Spring-managed component. Spring
    ‘s component scanning mechanism can now pick it up and pull it into the application environment.
  • @Controller: This marks a class as a Spring Web MVC controller. Beans marked with it are automatically imported into the IoC container.
  • @Service: This annotation is a specialization of the component annotation. It does not provide any other behavior to the @Component annotation. You can use @Service
    instead of @Component in service layer classes as it specifies the intent in a better way.
  • @Repository: This annotation is a specialization of the @Component annotation with similar purpose and functionality. It provides additional benefits to DAOs. It imports the DAO
    into the IoC container and makes unchecked exceptions eligible for conversion to Spring DataAccessException.

4.4. What is the use of the @Required annotation?

@Required is applied to bean property setter methods. This annotation only indicates that the affected bean properties must be populated at configuration time using explicit property values ​​in the bean definition or using autowiring. If the affected bean properties have not been populated, the container will throw a BeanInitializationException.
Example:

public class Employee {
    private String name;
    @Required
    public void setName(String name){
        this.name=name;
    }


    public string getName(){
        return name;
    }
}

4.5. What is the use of the @Autowired annotation?

@Autowired provides more precise control over where and how autowiring should occur. This annotation is used to autowire beans on setter methods, constructors, properties or methods with arbitrary names or multiple parameters. By default it is type-driven injection.

public class Employee {
    private String name;
    @Autowired
    public void setName(String name) {
        this.name=name;
    }
    public string getName(){
        return name;
    }
}

4.6. What is the use of the @Qualifier annotation?

When you create multiple beans of the same type and want to wire only one of them with properties, you can use the @Qualifier annotation and @Autowired to disambiguate by specifying which exact bean should be wired.
For example, here we have two classes, Employee and EmpAccount. In EmpAccount, use @Qualifier to specify that the bean with id emp1 must be wired.

public class Employee {
    private String name;
    @Autowired
    public void setName(String name) {
        this.name=name;
    }
    public string getName() {
        return name;
    }
}

EmpAccount.java

public class EmpAccount {
    private Employee emp;

    @Autowired
    @Qualifier(emp1)
    public void showName() {
        System.out.println(“Employee name : ”+emp.getName);
    }
}

4.7. What is the use of the @RequestMapping annotation?

The @RequestMapping annotation is used to map a specific HTTP request method to a specific class/method in the controller that will handle the corresponding request. This annotation can be applied at two levels:

  • Class level: Map the requested URL
  • Method level: mapping URLs and HTTP request methods

5. Data access

5.1. What is the use of spring DAO?

Spring DAO makes it easier for data access technologies like JDBC, Hibernate or JDO to work in a uniform way. This makes it easy for users to switch between persistence technologies. It also allows you to write code without thinking about catching exceptions that are different for each technology.

5.2. List the exceptions thrown by Spring DAO.

5.3. What classes exist in the spring JDBC API?

  • JdbcTemplate

  • SimpleJdbcTemplate

  • NamedParameterJdbcTemplate

  • SimpleJdbcInsert

  • SimpleJdbcCall

5.4. What are the ways to access Hibernate using Spring?

We can access Hibernate with Spring in two ways:

  1. Inversion of Control with Hibernate Templates and Callbacks
  2. Extend HibernateDAOSupport and apply AOP interceptor node

5.5. List the transaction management types supported by spring

Spring supports two types of transaction management:

  1. Programmatic Transaction Management: In this process, transactions are managed with the help of programming. It gives you great flexibility but is very difficult to maintain.
  2. Declarative transaction management: Here, transaction management is separated from business code. Transactions are managed using only annotations or XML-based configuration.

5.6. Which ORM frameworks does Spring support

  • Hibernate
  • iBatis
  • JPA
  • JDO
  • OJB

6、AOP

6.1. What is AOP?

AOP (Aspect-Oriented Programming), that is, aspect-oriented programming, which complements OOP (Object-Oriented Programming, object-oriented programming), provides a different perspective of abstract software structure from OOP.
In OOP, we use class (class) As our basic unit, and the basic unit in AOP is Aspect

6.2. What are the Aspect, Advice, Pointcut, JointPoint and Advice parameters in AOP?

  1. Aspect – Aspect is a class that implements cross-cutting issues such as transaction management. Aspects can be plain classes that are configured and then configured in Spring Bean configuration files, or we can use Spring AspectJ support to declare classes as Aspects using the @Aspect annotation.
  2. Advice – Advice is the action taken for a specific JoinPoint. In programming terms, they are methods that execute when a specific JoinPoint with a matching pointcut is reached in the application. You can think of Advice as a Spring interceptor (Interceptor) or Servlet filter (filter).
  3. Advice Arguments – We can pass arguments in the advice method. We can use args() expressions in pointcuts to apply to any method that matches the argument pattern. If we use it, then we need to use the same name in the advice method that determines the parameter type.
  4. Pointcut – Pointcut is a regular expression that matches JoinPoint to determine if Advice needs to be executed. Pointcut uses a different type of expression that matches JoinPoint. The Spring Framework uses the AspectJ Pointcut expression language to determine the JoinPoint to which the advice method will be applied.
  5. JoinPoint – A JoinPoint is a specific point in an application such as method execution, exception handling, changing object variable values, etc. In Spring AOP, JoinPoint is always the executor of a method.

6.3. What is Advice?

The action taken by the Aspect at a particular JoinPoint is called Advice. Spring AOP uses an Advice as an interceptor, maintaining a series of interceptors “around” the JoinPoint.

6.4. What types of Advice are there?

  • Before – These types of Advice are executed before the joinpoint method and are marked with the @Before annotation for configuration.
  • After Returning – These types of Advice are executed after the join point method is executed normally and
    are configured using the @AfterReturning annotation tag.
  • After Throwing – These types of advice are only executed when the joinpoint method exits by throwing an exception and marking the configuration with the @AfterThrowing annotation.
  • After (finally) – These types of Advice are executed after the join point method, regardless of whether the method exits normally or abnormally, and is marked with the @After annotation.
  • Around – These types of Advice are executed before and after the join point and are marked with the @Around annotation for configuration.

6.5. Point out the difference between concern and cross-cutting concern in spring aop.

A concern is the behavior we want to define in a specific module of the application. It can be defined as the function we want to achieve.
A cross-cutting concern is an application-wide behavior that affects the entire application. For example, logging, security, and data transfer are concerns that nearly every module of an application needs to focus on, so they are cross-cutting concerns.

6.6. What are the implementation methods of AOP?

The technologies for implementing AOP are mainly divided into two categories:

  • Static proxy – refers to using the commands provided by the AOP framework to compile, so that the AOP proxy class can be generated during the compilation phase, so it is also called compile-time enhancement;

  • compile-time weaving (special compiler implementation)

  • Classload-time weaving (special classloader implementation).

  • Dynamic proxies – AOP dynamic proxy classes are generated “temporarily” in memory at runtime, and are therefore also known as runtime enhancements.

  • JDK dynamic proxy

  • CGLIB

6.7. What is the difference between Spring AOP and AspectJ AOP?

Spring AOP is implemented based on dynamic proxy; AspectJ is implemented based on static proxy.
Spring AOP only supports PointCuts at the method level; providing full AOP support, it also supports PointCuts at the property level.

6.8. How to understand proxies in Spring?

Objects created after applying advice to a target object are called proxies. In the case of client objects, the target object and the proxy object are the same.

Advice + Target Object = Proxy

6.9. What is Weaving?

Linking an aspect with other application types or objects in order to create an advice object is called weaving. In Spring AOP, weaving is performed at runtime. Please refer to the image below:

7、MVC

7.1. What is the use of the Spring MVC framework?

The Spring Web MVC framework provides a model-view-controller architecture and ready-to-use components for developing flexible and loosely coupled web applications. The MVC pattern helps to separate different aspects of an application such as input logic, business logic and UI logic while providing loose coupling between all these elements.

7.2. Describe the workflow of DispatcherServlet

The workflow of DispatcherServlet can be illustrated with a picture:

  1. Send an HTTP request to the server, and the request is captured by the front controller DispatcherServlet.
  2. DispatcherServlet parses the requested URL according to the configuration in -servlet.xml, and obtains the request resource identifier (URI). Then according to the URI, call HandlerMapping to obtain all related objects configured by the Handler (including the Handler object and the interceptor corresponding to the Handler object), and finally return it in the form of a HandlerExecutionChain object.
  3. DispatcherServlet selects a suitable HandlerAdapter according to the obtained Handler. (Note: If the HandlerAdapter is successfully obtained, the interceptor’s
    preHandler(…) method will be executed at this time).
  4. Extract the model data in the Request, fill in the Handler input parameters, and start executing the Handler (Controller). In the process of filling in the Handler’s input parameters, according to your configuration, Spring will do some additional work for you:

  5. HttpMessageConveter: Convert the request message (such as Json, xml and other data) into an object, and convert the object into the specified response information.

  6. Data transformation: perform data transformation on the request message. Such as String converted into Integer, Double and so on.

  7. Data Root Formatting: Format the data of the request message. Such as converting strings into formatted numbers or formatted dates, etc.

  8. Data verification: verify the validity of the data (length, format, etc.), and store the verification result in BindingResult or Error.

  9. After Handler(Controller) is executed, it returns a ModelAndView object to DispatcherServlet;

  10. According to the returned ModelAndView, select a suitable ViewResolver (must be the ViewResolver registered in the Spring container) and return it to DispatcherServlet.
  11. ViewResolver combines Model and View to render views.
  12. The view is responsible for returning the rendered result to the client.

7.3. Introducing WebApplicationContext

WebApplicationContext is an extension of ApplicationContext. It has some extra features required for web applications. It differs from the normal ApplicationContext in its ability to resolve the subject and decide which servlet to associate with.

A Word of the Day
“””””” Even small sails can sail far away
If this article is helpful to everyone, please like, favorite, and forward!

Leave a Comment

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