A summary of the most classic 26 Spring interview questions on the entire network (with answers, please give me a thumbs up after reading it!)

Foreword:

This article mainly introduces the relevant information of the 26 Spring classic interview questions (with answers). I saw it on the Internet and thought it was pretty good. Now I share it with you. If you are the same as the online author, please notify me, I will Attach the link. Let's follow the editor to take a look, I hope it will help you.
Insert picture description here

In addition, I have compiled and collected interview knowledge points from more than 20 years of companies, as well as various Java core knowledge points for free to share with you. The following are only some screenshots. If you want information, you can click 1149778920 to receive the code: qf.
Insert picture description here

1. Basic issues

1. What are the main functions of different versions of Spring Framework?
Insert picture description here2. 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.

3. List the advantages of 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, which has continuous integration and testability.
JDBC is simplified due to dependency injection and inversion of control.
It is open source and free.

4. What are the different functions of 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 life cycle and configuration of the object (Bean).
MVC-Provides a high degree of configurability for web applications, and the integration of other frameworks is also very convenient.
Transaction Management-Provides a common abstraction layer for transaction management. Spring's transaction support can also be used in environments with fewer containers.
JDBC Exceptions-Spring's JDBC abstraction layer provides an exception hierarchy and simplifies error handling strategies.

5. How many modules are there in Spring Framework and what are they?
Insert picture description here
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: AOP-this layer supports aspect-oriented programming

  • Web

  • Web – Servlet

  • Web – Socket

  • Web-Portlet
    -Instrumentation-This layer provides support for class detection and class loader implementation.

Test-This layer provides support for testing using JUnit and TestNG.

Several miscellaneous modules:

  • Messaging-This module provides support for STOMP. It also supports an annotation programming model, which is used to route and process STOMP messages from WebSocket clients.
  • Aspects-This module provides support for integration with AspectJ.

Two, dependency injection (Ioc)

1. What is the Spring IOC container?
The core of the Spring framework is the Spring container. The container creates objects, assembles them, configures them, and manages their complete life cycle. The Spring container uses dependency injection to manage the components that make up the application. The container receives instructions for instantiation, configuration, and assembly of objects by reading the provided configuration metadata. The metadata can be provided through XML, Java annotations or Java code.
Insert picture description here
2. What is dependency injection?

In dependency injection, you don't have to create objects, but you must describe how to create them. You are not directly connecting components and services in the code, but describing which components in the configuration file require which services. They are assembled by the IoC container.

3. How many ways can dependency injection be accomplished?

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 are used.

4. Distinguish between constructor injection and setter injection.
Insert picture description here

5. How many kinds of IOC containers are there in spring?

BeanFactory-BeanFactory is like a factory class that contains a collection of beans. It will instantiate the bean when requested by the client.

ApplicationContext-The ApplicationContext interface extends the BeanFactory interface. It provides some additional functions on the basis of BeanFactory.

Three, Beans

1. What is a spring bean?

They are the objects that form the backbone of the user's application.
Beans are managed by the Spring IoC container.
They are instantiated, configured, assembled and managed by the Spring IoC container.
Bean is created based on the configuration metadata provided by the user to the container.

2. What configuration methods does spring provide?

Based on xml configuration

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

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

Configuration based on annotations

Instead of using XML to describe bean assembly, you can configure the bean as the component class itself by using annotations on related 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 by using @Bean and @Configuration.

  • The @Bean annotation plays the same role as the element.

  • The @Configuration class allows you to define inter-bean dependencies by simply calling other @Bean methods in the same class.

E.g:

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

3. Does spring support centralized bean scope?

Spring beans support 5 scopes:

  • Singleton-There is only one singleton per Spring IoC container.
  • Prototype-Each request will generate a new instance.
  • Request-Each HTTP request will generate a new instance, 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 in 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 different portlets that constitute a portlet web application. The beans defined in the global session scope are limited to the life cycle scope of the global portlet Session. If you use the global session scope to identify beans in the web, the web will automatically be used as a session type.
    The last three are available only when the user is using the Web-enabled ApplicationContext.

4. What is the life cycle of the spring bean container?

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

  • The Spring container instantiates the bean according to the bean definition in the configuration.

  • Spring uses dependency injection to fill in all properties, such as the configuration defined in the bean.

  • If the bean implements the BeanNameAware interface, the factory calls setBeanName() by passing the bean ID.

  • If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory() by passing an instance of itself.

  • If there are any BeanPostProcessors associated with the bean, call the
    preProcessBeforeInitialization() method.

  • If the init method (the init-method attribute) is specified for the bean, it will be called.

  • Finally, if there are any BeanPostProcessors associated with the bean, the
    postProcessAfterInitialization() method will be called .

  • If the bean implements the DisposableBean interface, destroy() will be called when the spring container is closed.

  • If the destroy method (destroy-method attribute of) is specified for the bean, it will be called.
    Insert the picture here to describe
    5. What is the inner bean of spring?

The bean can only be declared as an inner bean if it is used as a property of another bean. In order 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.

E.g:

Suppose we have a Student class, which references the Person class. Here we will only 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 name="person">
            <!--This is inner bean -->
            <bean class="com.edureka.Person">
                <property name="name" value=“Scott"></property>
                <property name="address" value=“Bangalore"></property>
            </bean>
        </property>
    </bean>

Four, annotation

1. What important Spring annotations have you used?

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

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

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

  • @Component: This marks the java class as bean. It is a general stereotype for any Spring management 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 will be automatically imported into the IoC container.
  • @Service: This annotation is a specialization of component annotation. It does not provide any other behavior for the @Component annotation. You can use @Service instead of-@Component in the service layer class because it specifies the intent in a better way.
  • @Repository: This annotation is a specialization of the @Component annotation with similar uses and functions. It provides additional benefits for DAO. It imports DAO into the IoC container and makes unchecked exceptions eligible to be converted to Spring DataAccessException.
    3. What is the use of @Required annotation?

@Required is applied to bean property setter methods. This annotation only indicates that you must use explicit property values ​​in the bean definition or use autowiring to populate the affected bean properties during configuration. 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. What is the use of @Autowired annotation?

@Autowired can more accurately control where and how the automatic assembly should be performed. This annotation is used to automatically assemble 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;
}
}

Five, data access

1. What is the use of spring DAO?

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

2. List the exceptions thrown by Spring DAO.
Insert picture description here

3. What classes exist in the spring JDBC API?

JdbcTemplate
SimpleJdbcTemplate
NamedParameterJdbcTemplate
SimpleJdbcInsert
SimpleJdbcCall

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

We can use Spring to access Hibernate in two ways:

  • Use Hibernate templates and callbacks for inversion of control

  • Extend HibernateDAOSupport and apply AOP interceptor node

5. List the transaction management types supported by spring

Spring supports two types of transaction management:

  • Programmatic transaction management: During this process, affairs are managed with the help of programming. It offers you great flexibility, but it is very difficult to maintain.

  • Declarative transaction management: Here, transaction management is separated from business code. Only use annotations or XML-based configuration to manage transactions.

Six, AOP

AOP (Aspect-Oriented Programming), that is, aspect-oriented programming, it complements OOP (Object-Oriented Programming, object-oriented programming), and provides a perspective of abstract software structure that is different from OOP. In OOP, we take classes as Our basic unit, and the basic unit in AOP is Aspect (section)

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

Insert picture description here

  • Aspect-Aspect is a class that implements cross-cutting issues, such as transaction management. The aspect can be a common class configured and then configured in the Spring Bean configuration file, or we can use Spring AspectJ to support the @Aspect annotation to declare the class as an Aspect.
  • Advice-Advice is the action taken for a specific JoinPoint. In terms of programming, they are methods that are executed when a specific JoinPoint with a matching pointcut is reached in the application. You can think of Advice as a Spring Interceptor or a Servlet filter.
  • Advice Arguments-We can pass parameters in the advice method. We can use the args() expression in the pointcut to apply to any method that matches the parameter pattern. If we use it, then we need to use the same name in the advice method that determines the parameter type.
  • Pointcut-Pointcut is a regular expression that matches JoinPoint and is used to determine whether advice needs to be executed. Pointcut uses different types of expressions that match JoinPoint. The Spring framework uses the AspectJ Pointcut expression language to determine the JoinPoint that will apply the notification method.
  • JoinPoint-JoinPoint is a specific point in the application, such as method execution, exception handling, changing object variable values, etc. In Spring AOP, JoinPoint is always the executor of the method.

七、MVC

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 separate different aspects of the application, such as input logic, business logic, and UI logic, while providing loose coupling between all these elements.

Describe the workflow of
DispatcherServlet The workflow of DispatcherServlet can be illustrated by a picture:
Insert picture description here

  • Send an HTTP request to the server, and the request is captured by the front controller DispatcherServlet.

  • DispatcherServlet parses the requested URL according to the configuration in -servlet.xml to obtain the requested resource identifier (URI). Then according to the URI, call HandlerMapping to obtain all related objects (including the Handler object and the interceptor corresponding to the Handler object) of the Handler configuration, and finally return it in the form of a HandlerExecutionChain object.

  • DispatcherServlet selects an appropriate HandlerAdapter according to the Handler obtained. (Note: If the HandlerAdapter is successfully obtained, the interceptor's preHandler(...) method will be executed at this time).

  • Extract the model data in the Request, fill in the Handler input parameters, and start to execute the Handler (Controller). In the process of filling in the parameters of the Handler, Spring will help you do some extra work according to your configuration: After the Handler (Controller) is executed, it returns a ModelAndView object to the DispatcherServlet;

HttpMessageConveter: Convert the request message (such as Json, XML, etc.) into an object, and convert the object into the specified response message.
Data conversion: Data conversion of the request message. For example, String is converted to Integer, Double, etc.
Data root formatting: Data formatting of request messages. Such as converting a string into a formatted number or formatted date.
Data verification: Verify the validity of the data (length, format, etc.), and store the verification result in BindingResult or Error.

  • According to the returned ModelAndView, select a suitable ViewResolver (must be a ViewResolver registered in the Spring container) and return it to DispatcherServlet.

  • ViewResolver combines Model and View to render the view.

  • The view is responsible for returning the rendering result to the client.

Final words

No matter which company it is, it attaches great importance to Spring framework technology and foundation, so don't underestimate any knowledge. The interview is a two-way selection process. Don't go to the interview with a fearful attitude, which is not conducive to your own performance.
At the same time, it should not only be the salary, but also whether you really like this company. Okay, I hope this article is helpful to everyone!
In addition, I have compiled and collected interview knowledge points from more than 20 years of companies, as well as various Java core knowledge points for free to share with you.
The following are only some screenshots. If you want information, you can also click 1149778920 to receive the code: qf.

Insert picture description here

Guess you like

Origin blog.csdn.net/SpringBoot_/article/details/109036865