Top Spring Framework Interview Questions – 顶尖的Spring框架面试问题

最后修改: 2017年 6月 13日

中文/混合/英文(键盘快捷键:t)

Table of Contents

目录

 

 

 

 

 

1. Overview

1.概述

In this tutorial, we’re going to look at some of the most common Spring-related questions that might pop up during a job interview.

在本教程中,我们将看看在求职面试中可能出现的一些最常见的与Spring有关的问题。

2. Spring Core

2.Spring核心

Q1. What Is Spring Framework?

Q1.什么是Spring框架?

Spring is the most broadly used framework for the development of Java Enterprise Edition applications. Further, the core features of Spring can be used in developing any Java application.

Spring是开发Java企业版应用程序的最广泛使用的框架。此外,Spring的核心功能可用于开发任何Java应用程序。

We use its extensions for building various web applications on top of the Jakarta EE platform. We can also just use its dependency injection provisions in simple standalone applications.

我们使用它的扩展功能在Jakarta EE平台之上构建各种网络应用。我们也可以只在简单的独立应用中使用它的依赖注入条款。

Q2. What Are the Benefits of Using Spring?

Q2.使用Spring的好处是什么?

Spring targets to make Jakarta EE development easier, so let’s look at the advantages:

Spring的目标是使Jakarta EE的开发更容易,所以我们来看看它的优点。

  • Lightweight – There is a slight overhead of using the framework in development.
  • Inversion of Control (IoC) – Spring container takes care of wiring dependencies of various objects instead of creating or looking for dependent objects.
  • Aspect-Oriented Programming (AOP) – Spring supports AOP to separate business logic from system services.
  • IoC container – manages Spring Bean life cycle and project-specific configurations
  • MVC framework – used to create web applications or RESTful web services, capable of returning XML/JSON responses
  • Transaction management – reduces the amount of boilerplate code in JDBC operations, file uploading, etc., either by using Java annotations or by Spring Bean XML configuration file
  • Exception Handling – Spring provides a convenient API for translating technology-specific exceptions into unchecked exceptions.

Q3. What Spring Sub-Projects Do You Know? Describe Them Briefly.

Q3.你知道哪些Spring子项目?简要描述一下

  • Core – a key module that provides fundamental parts of the framework, such as IoC or DI
  • JDBC – enables a JDBC-abstraction layer that removes the need to do JDBC coding for specific vendor databases
  • ORM integration – provides integration layers for popular object-relational mapping APIs, such as JPA, JDO and Hibernate
  • Web – a web-oriented integration module that provides multipart file upload, Servlet listeners and web-oriented application context functionalities
  • MVC framework – a web module implementing the Model View Controller design pattern
  • AOP module – aspect-oriented programming implementation allowing the definition of clean method-interceptors and pointcuts

Q4. What Is Dependency Injection?

Q4.什么是依赖性注入?

Dependency injection, an aspect of Inversion of Control (IoC), is a general concept stating that we do not create our objects manually but instead describe how they should be created. Then an IoC container will instantiate required classes if needed.

依赖性注入是控制反转(IoC)的一个方面,是一个一般的概念,说明我们不手动创建我们的对象,而是描述它们应该如何被创建。然后,如果需要的话,IoC容器将实例化所需的类。

For more details, please look here.

欲了解更多详情,请查看这里

Q5. How Can We Inject Beans in Spring?

Q5.我们如何在Spring注入Bean?

A few different options exist in order to inject Spring beans:

为了注入Spring Bean,存在一些不同的选择。

  • Setter injection
  • Constructor injection
  • Field injection

The configuration can be done using XML files or annotations.

配置可以使用XML文件或注释来完成。

For more details, check this article.

欲了解更多细节,请查看这篇文章

Q6. Which Is the Best Way of Injecting Beans and Why?

Q6.哪种是注射Bean的最佳方式,为什么?

The recommended approach is to use constructor arguments for mandatory dependencies and setters for optional ones. This is because constructor injection allows injecting values to immutable fields and makes testing easier.

推荐的方法是对强制性依赖使用构造函数参数,对可选依赖使用设置器。这是因为构造函数注入允许向不可变的字段注入值,使测试更容易。

Q7. What Is the Difference Between BeanFactory and ApplicationContext?

Q7.BeanFactory和ApplicationContext之间的区别是什么?

BeanFactory is an interface representing a container that provides and manages bean instances. The default implementation instantiates beans lazily when getBean() is called.

BeanFactory是一个接口,代表一个提供和管理Bean实例的容器。默认的实现是在调用getBean()时懒散地将Bean实例化。

In contrast, ApplicationContext is an interface representing a container holding all information, metadata and beans in the application. It also extends the BeanFactory interface, but the default implementation instantiates beans eagerly when the application starts. However, this behavior can be overridden for individual beans.

相比之下,ApplicationContext是一个接口,它代表了一个容纳应用程序中所有信息、元数据和bean的容器。它也扩展了BeanFactory接口,但默认实现是在应用程序启动时急切地实例化Bean。然而,这种行为可以为单个Bean重写。

For all differences, please refer to the documentation.

对于所有的差异,请参考文档

Q8. What Is a Spring Bean?

Q8.什么是SpringBean?

The Spring Beans are Java Objects that are initialized by the Spring IoC container.

Spring Bean是由Spring IoC容器初始化的Java对象。

Q9. What Is the Default Bean Scope in Spring Framework?

Q9.什么是Spring框架中的默认Bean范围?

By default, a Spring Bean is initialized as a singleton.

默认情况下,Spring Bean被初始化为一个singleton

Q10. How to Define the Scope of a Bean?

Q10.如何定义Bean的范围?

In order to set Spring Bean’s scope, we can use @Scope annotation or “scope” attribute in XML configuration files. Note that there are five supported scopes:

为了设置Spring Bean的作用域,我们可以在XML配置文件中使用@Scope注解或 “范围 “属性。请注意,有五个支持的作用域。

  • Singleton
  • Prototype
  • Request
  • Session
  • Global-session

For differences, please look here.

关于差异,请看这里

Q11. Are Singleton Beans Thread-Safe?

Q11.单子Bean是线程安全的吗?

No, singleton beans are not thread-safe, as thread safety is about execution, whereas the singleton is a design pattern focusing on creation. Thread safety depends only on the bean implementation itself.

不,单子Bean不是线程安全的,因为线程安全是关于执行的,而单子是一种专注于创建的设计模式。线程安全只取决于Bean的实现本身。

Q12. What Does the Spring Bean Life Cycle Look Like?

Q12.SpringBean的生命周期是什么样的?

First, a Spring bean needs to be instantiated based on Java or XML bean definition. It may also be required to perform some initialization to get it into a usable state. After that, when the bean is no longer required, it will be removed from the IoC container.

首先,Spring Bean需要根据Java或XML Bean定义进行实例化。它可能还需要执行一些初始化,使其进入可用状态。之后,当不再需要该Bean时,它将被从IoC容器中删除。

The whole cycle with all initialization methods is shown in the image (source):

带有所有初始化方法的整个周期显示在图片中(来源)。

Spring Bean Life Cycle

Q13. What Is the Spring Java-Based Configuration?

Q13.什么是基于Spring Java的配置?

It’s one of the ways of configuring Spring-based applications in a type-safe manner. It’s an alternative to the XML-based configuration.

它是以类型安全的方式配置基于Spring的应用程序的方法之一。它是基于XML的配置的替代品。

Also, to migrate a project from XML to Java config, please refer to this article.

此外,要将一个项目从XML迁移到Java配置,请参考这篇文章

Q14. Can We Have Multiple Spring Configuration Files in One Project?

Q14.我们可以在一个项目中拥有多个Spring配置文件吗?

Yes, in large projects, having multiple Spring configurations is recommended to increase maintainability and modularity.

是的,在大型项目中,建议拥有多个Spring配置以提高可维护性和模块化。

We can load multiple Java-based configuration files:

我们可以加载多个基于Java的配置文件。

@Configuration
@Import({MainConfig.class, SchedulerConfig.class})
public class AppConfig {

Or we can load one XML file that will contain all other configs:

或者我们可以加载一个XML文件,该文件将包含所有其他配置。

ApplicationContext context = new ClassPathXmlApplicationContext("spring-all.xml");

And inside this XML file we’ll have the following:

在这个XML文件中,我们将有以下内容。

<import resource="main.xml"/>
<import resource="scheduler.xml"/>

Q15. What Is Spring Security?

Q15.什么是Spring Security?

Spring Security is a separate module of the Spring framework that focuses on providing authentication and authorization methods in Java applications. It also takes care of most of the common security vulnerabilities such as CSRF attacks.

Spring Security是Spring框架的一个独立模块,主要是在Java应用程序中提供认证和授权方法。它还负责处理大多数常见的安全漏洞,如CSRF攻击。

To use Spring Security in web applications, we can get started with the simple annotation @EnableWebSecurity.

要在Web应用程序中使用Spring Security,我们可以从简单的注解@EnableWebSecurity开始。

For more information, we have a whole series of articles related to security.

欲了解更多信息,我们有一整套与安全有关的文章。

Q16. What Is Spring Boot?

Q16.什么是Spring Boot?

Spring Boot is a project that provides a pre-configured set of frameworks to reduce boilerplate configuration. This way, we can have a Spring application up and running with the smallest amount of code.

Spring Boot是一个项目,它提供了一套预配置的框架,以减少模板配置。这样,我们就可以用最少的代码来启动和运行一个Spring应用程序。

Q17. Name Some of the Design Patterns Used in the Spring Framework?

Q17.说出Spring框架中使用的一些设计模式?

  • Singleton Pattern – singleton-scoped beans
  • Factory Pattern – Bean Factory classes
  • Prototype Pattern – prototype-scoped beans
  • Adapter Pattern – Spring Web and Spring MVC
  • Proxy Pattern – Spring Aspect-Oriented Programming support
  • Template Method Pattern – JdbcTemplate, HibernateTemplate, etc.
  • Front Controller – Spring MVC DispatcherServlet
  • Data Access Object – Spring DAO support
  • Model View Controller – Spring MVC

Q18. How Does the Scope Prototype Work?

Q18.范围原型是如何工作的?

Scope prototype means that every time we call for an instance of the Bean, Spring will create a new instance and return it. This differs from the default singleton scope, where a single object instance is instantiated once per Spring IoC container.

作用域prototype意味着每次我们调用Bean的一个实例时,Spring都会创建一个新的实例并返回它。这与默认的singleton范围不同,在这个范围内,每个Spring IoC容器只实例化一个对象实例。

3. Spring Web MVC

3.Spring Web MVC

Q19. How to Get ServletContext and ServletConfig Objects in a Spring Bean?

Q19.如何在Spring Bean中获取ServletContextServletConfig对象?

We can do either by implementing Spring-aware interfaces. The complete list is available here.

我们可以通过实现Spring感知的接口来做到这一点。完整的列表可在这里获得。

We could also use @Autowired annotation on those beans:

我们也可以在这些Bean上使用@Autowired注解。

@Autowired
ServletContext servletContext;

@Autowired
ServletConfig servletConfig;

Q20. What Is a Controller in Spring MVC?

Q20.什么是Spring MVC中的控制器?

Simply put, all the requests processed by the DispatcherServlet are directed to classes annotated with @Controller. Each controller class maps one or more requests to methods that process and execute the requests with provided inputs.

简单地说,由DispatcherServlet处理的所有请求都被引导到用@Controller注释的类。每个控制器类将一个或多个请求映射到处理和执行请求的方法中,并提供输入。

To take a step back, we recommend having a look at the concept of the Front Controller in the typical Spring MVC architecture.

退一步讲,我们建议看看典型的Spring MVC架构中的前端控制器的概念

Q21. How Does the @RequestMapping Annotation Work?

Q21.@RequestMapping注释是如何工作的?

The @RequestMapping annotation is used to map web requests to Spring Controller methods. In addition to simple use cases, we can use it for mapping of HTTP headers, binding parts of the URI with @PathVariable, and working with URI parameters and the @RequestParam annotation.

@RequestMapping注解用于将Web请求映射到Spring控制器方法。除了简单的用例外,我们还可以用它来映射HTTP头,用@PathVariable绑定URI的部分内容,以及处理URI参数和@RequestParam注解。

More details on @RequestMapping are available here.

关于@RequestMapping的更多细节可在此处获得。

For more Spring MVC questions, please check out our article on Spring MVC interview questions.

更多Spring MVC问题,请查看我们的文章Spring MVC面试问题

4. Spring Data Access

4.Spring数据访问

Q22. What Is Spring JdbcTemplate Class and How to Use It?

Q22.什么是Spring JdbcTemplate类以及如何使用它?

The Spring JDBC template is the primary API through which we can access database operations logic that we’re interested in:

Spring JDBC模板是主要的API,我们可以通过它访问我们感兴趣的数据库操作逻辑。

  • Creation and closing of connections
  • Executing statements and stored procedure calls
  • Iterating over the ResultSet and returning results

In order to use it, we’ll need to define the simple configuration of DataSource:

为了使用它,我们需要定义DataSource的简单配置。

@Configuration
@ComponentScan("org.baeldung.jdbc")
public class SpringJdbcConfig {
    @Bean
    public DataSource mysqlDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/springjdbc");
        dataSource.setUsername("guest_user");
        dataSource.setPassword("guest_password");
 
        return dataSource;
    }
}

For further explanation, check out this quick article.

如需进一步解释,请查看这篇快速文章

Q23. How to Enable Transactions in Spring and What Are Their Benefits?

Q23.如何在Spring中启用事务,其好处是什么?

There are two distinct ways to configure Transactions — with annotations or by using Aspect-Oriented Programming (AOP) — each with their advantages.

有两种不同的方式来配置Transactions–使用注解或使用面向方面的编程(AOP)–每种方式都有其优势。

Here are the benefits of using Spring Transactions, according to the official docs:

根据官方文档,以下是使用Spring Transactions的好处。

  • Provide a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA and JDO
  • Support declarative transaction management
  • Provide a simpler API for programmatic transaction management than some complex transaction APIs such as JTA
  • Integrate very well with Spring’s various data access abstractions

Q24. What Is Spring DAO?

Q24.什么是Spring DAO?

Spring Data Access Object (DAO) is Spring’s support provided to work with data access technologies like JDBC, Hibernate and JPA in a consistent and easy way.

Spring数据访问对象(DAO)是Spring提供的支持,以一致和简单的方式与JDBC、Hibernate和JPA等数据访问技术合作。

There is an entire series discussing persistence in Spring that provides a more in-depth look.

有一个整个系列讨论了Spring中的持久性,提供了更深入的研究。

5. Spring Aspect-Oriented Programming

5.面向方面的Spring编程

Q25. What Is Aspect-Oriented Programming (AOP)?

Q25.什么是面向方面的编程(AOP)?

Aspects enable the modularization of cross-cutting concerns such as transaction management that span multiple types and objects by adding extra behavior to already existing code without modifying affected classes.

Aspects通过向已存在的代码添加额外的行为而无需修改受影响的类,实现了跨领域关注点的模块化,如跨越多种类型和对象的事务管理。

Here is the example of aspect-based execution time logging.

下面是基于方面的执行时间记录的例子。

Q26. What Are Aspect, Advice, Pointcut and JoinPoint in AOP?

Q26.什么是AOP中的Aspect、Advice、Pointcut和JoinPoint?

  • Aspect – a class that implements cross-cutting concerns, such as transaction management
  • Advice – the methods that get executed when a specific JoinPoint with matching Pointcut is reached in the application
  • Pointcut – a set of regular expressions that are matched with JoinPoint to determine whether Advice needs to be executed or not
  • JoinPoint – a point during the execution of a program, such as the execution of a method or the handling of an exception

Q27. What Is Weaving?

Q27.什么是编织?

According to the official docs, weaving is a process that links aspects with other application types or objects to create an advised object. This can be done at compile time, load time, or runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime.

根据官方文档编织是一个将方面与其他应用程序类型或对象联系起来以创建一个建议对象的过程。这可以在编译时、加载时或运行时完成。Spring AOP 与其他纯 Java AOP 框架一样,在运行时执行织入

6. Spring 5

6. Spring5

Q28. What Is Reactive Programming?

Q28.什么是反应式编程?

Reactive programming is about non-blocking, event-driven applications that scale with a small number of threads, with back pressure being a key ingredient that aims to ensure producers don’t overwhelm consumers.

反应式编程是关于非阻塞的、事件驱动的应用程序,可以用少量的线程进行扩展,背压是一个关键因素,旨在确保生产者不会压倒消费者。

These are the primary benefits of reactive programming:

这些是反应式编程的主要好处。

  • Increased utilization of computing resources on multicore and multi-CPU hardware
  • Increased performance by reducing serialization

Reactive programming is generally event-driven, in contrast to reactive systems, which are message-driven. So, using reactive programming does not mean we’re building a reactive system, which is an architectural style.

反应式编程通常是事件驱动的,与反应式系统相反,后者是消息驱动的。所以,使用反应式编程并不意味着我们在构建一个反应式系统,这是一种架构风格。

However, reactive programming may be used as a means to implement reactive systems if we follow the Reactive Manifesto, which is quite vital to understand.

然而,如果我们遵循反应式宣言,就可以将反应式编程作为实现反应式系统的一种手段,这一点的理解相当关键。

Based on this, reactive systems have four important characteristics:

在此基础上,反应式系统有四个重要特征。

  • Responsive – The system should respond in a timely manner.
  • Resilient – In case the system faces any failure, it should stay responsive.
  • Elastic – Reactive systems can react to changes and stay responsive under varying workload.
  • Message-driven – Reactive systems need to establish a boundary between components by relying on asynchronous message passing.

Q29. What Is Spring WebFlux?

Q29.什么是Spring WebFlux?

Spring WebFlux is Spring’s reactive-stack web framework, and it’s an alternative to Spring MVC.

Spring WebFlux是Spring的反应堆Web框架,它是Spring MVC的替代品。

In order to achieve this reactive model and be highly scalable, the entire stack is non-blocking. Check out our tutorial on Spring 5 WebFlux for additional details.

为了实现这种反应式模型并具有高度的可扩展性,整个堆栈是无阻塞的。请查看我们的关于Spring 5 WebFlux的教程以了解更多细节。

Q30. What Are the Mono and Flux Types?

Q30.什么是单质和通量类型?

The WebFlux framework in Spring Framework 5 uses Reactor as its async foundation.

Spring Framework 5中的WebFlux框架使用Reactor作为其异步基础。

This project provides two core types: Mono to represent a single async value and Flux to represent a stream of async values. They both also implement the Publisher interface defined in the Reactive Streams specification.

这个项目提供了两个核心类型。Mono代表单个异步值,Flux代表异步值的流。它们都实现了Reactive Streams规范中定义的Publisher接口。

Mono implements Publisher and returns 0 or 1 elements:

Mono实现Publisher并返回0或1个元素。

public abstract class Mono<T> implements Publisher<T> {...}

And Flux implements Publisher and returns N elements:

Flux实现了Publisher并返回N元素。

public abstract class Flux<T> implements Publisher<T> {...}

By definition, the two types represent streams, and so they’re both lazy. This means nothing is executed until we consume the stream using the subscribe() method. Both types are also immutable, so calling any method will return a new instance of Flux or Mono.

根据定义,这两种类型代表流,所以它们都是懒惰的。这意味着在我们使用subscribe()方法消耗流之前,什么都不会被执行。这两种类型也都是不可改变的,所以调用任何方法都会返回一个新的FluxMono的实例。

Q31. What Is the Use of WebClient and WebTestClient?

Q31.什么是WebClientWebTestClient的用途?

WebClient is a component in the new Web Reactive framework that can act as a reactive client for performing non-blocking HTTP requests. Since it’s reactive client, it can handle reactive streams with back pressure, and it can take full advantage of Java 8 lambdas. It can also handle both sync and async scenarios.

WebClient是新的Web Reactive框架中的一个组件,可以作为一个反应式客户端来执行非阻塞的HTTP请求。由于它是反应式客户端,它可以处理具有反压的反应式流,并且可以充分利用Java 8 lambdas。它还可以处理同步和异步两种情况。

On the other hand, the WebTestClient is a similar class that we can use in tests. Basically, it’s a thin shell around the WebClient. It can connect to any server over an HTTP connection. It can also bind directly to WebFlux applications using mock request and response objects, without the need for an HTTP server.

另一方面,WebTestClient是一个类似的类,我们可以在测试中使用。基本上,它是一个围绕WebClient的薄壳。它可以通过HTTP连接连接到任何服务器。它还可以使用模拟的请求和响应对象直接绑定到WebFlux应用程序,而不需要HTTP服务器。

Q32. What Are the Disadvantages of Using Reactive Streams?

Q32.使用反应式流的缺点是什么?

There are some major disadvantages to using reactive streams:

使用反应式流有一些主要的缺点。

  • Troubleshooting a Reactive application is a bit difficult, so be sure to check out our tutorial on debugging reactive streams for some handy debugging tips.
  • There is limited support for reactive data stores since traditional relational data stores have yet to embrace the reactive paradigm.
  • There’s an extra learning curve when implementing.

Q33. Is Spring 5 Compatible With Older Versions of Java?

Q33.Spring 5是否与旧版本的Java兼容?

In order to take advantage of Java 8 features, the Spring codebase has been revamped. This means older versions of Java cannot be used. So, the framework requires a minimum of Java 8.

为了利用Java 8的特性,Spring的代码库已经进行了改造。这意味着不能使用旧版本的Java。因此,该框架至少需要使用Java 8。

Q34. How Does Spring 5 Integrate With JDK 9 Modularity?

Q34.Spring 5如何与JDK 9模块化整合?

In Spring 5, everything has been modularized. This way, we won’t be forced to import jars that may not have the functionalities we’re looking for.

在Spring 5中,一切都被模块化了。这样一来,我们就不会被迫导入那些可能不具备我们所需功能的罐子。

Please have a look at our guide to Java 9 modularity for an in-depth understanding of how this technology works.

请查看我们的Java 9 模块化指南,以深入了解该技术的工作原理。

Let’s see an example to understand the new module functionality in Java 9 and how to organize a Spring 5 project based on this concept.

让我们看一个例子来了解Java 9中的新模块功能,以及如何基于这个概念组织一个Spring 5项目。

We’ll first create a new class that contains a single method to return a String “HelloWorld”. We’ll place this within a new Java project — HelloWorldModule:

我们首先创建一个新的类,其中包含一个返回String“HelloWorld “的单一方法。我们将把它放在一个新的Java项目中–HelloWorldModule

package com.hello;
public class HelloWorld {
    public String sayHello(){
        return "HelloWorld";
    }
}

Then we create a new module:

然后我们创建一个新的模块。

module com.hello {
    export com.hello;
}

Now let’s create a new Java Project, HelloWorldClient, to consume the above module by defining a module:

现在让我们创建一个新的Java项目,HelloWorldClient,通过定义一个模块来消费上述模块。

module com.hello.client {
    requires com.hello;
}

The above module will be available for testing now:

上述模块现在就可以进行测试。

public class HelloWorldClient {
    public static void main(String[] args){
        HelloWorld helloWorld = new HelloWorld();
        log.info(helloWorld.sayHello());
    }
}

Q35. Can We Use Both Web MVC and WebFlux in the Same Application?

Q35.我们能否在同一个应用程序中同时使用Web MVC和WebFlux?

As of now, Spring Boot will only allow either Spring MVC or Spring WebFlux, as Spring Boot tries to auto-configure the context depending on the dependencies that exist in its classpath.

到目前为止,Spring Boot只允许Spring MVC或Spring WebFlux,因为Spring Boot试图根据其classpath中存在的依赖关系来自动配置上下文。

Also, Spring MVC cannot run on Netty. Moreover, MVC is a blocking paradigm and WebFlux is a non-blocking style. So, we shouldn’t be mixing both together because they serve different purposes.

另外,Spring MVC不能在Netty上运行。此外,MVC是一种阻塞式范式,而WebFlux是一种非阻塞式。所以,我们不应该把两者混在一起,因为它们的目的不同。

7. Conclusion

7.结论

In this extensive article, we’ve explored some of the most important questions for a technical interview all about Spring.

在这篇广泛的文章中,我们探讨了一些关于Spring的技术面试的最重要问题。

We hope that this article will help in upcoming Spring interviews. Good luck!

我们希望这篇文章能对即将到来的Spring面试有所帮助。祝您好运!

« Previous

Java Annotations Interview Questions (+ Answers)