A Comparison Between Spring and Spring Boot – Spring和Spring Boot之间的比较

最后修改: 2018年 9月 29日

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

1. Overview

1.概述

In this tutorial, we’re going to look at the differences between the standard Spring frameworks and Spring Boot.

在本教程中,我们要看一下标准Spring框架和Spring Boot之间的区别。

We’ll focus on and discuss how the modules of Spring, like MVC and Security, differ when used in core Spring versus when used with Boot.

我们将重点讨论Spring的模块,如MVC和Security,在核心Spring中使用与在Boot中使用有什么不同。

2. What Is Spring?

2.什么是Spring?

Simply put, the Spring framework provides comprehensive infrastructure support for developing Java applications.

简单地说,Spring框架为开发Java应用程序提供了全面的基础设施支持

It’s packed with some nice features like Dependency Injection, and out of the box modules like:

它包含了一些很好的功能,如依赖性注入,以及开箱即用的模块,如。

  • Spring JDBC
  • Spring MVC
  • Spring Security
  • Spring AOP
  • Spring ORM
  • Spring Test

These modules can drastically reduce the development time of an application.

这些模块可以极大地减少应用程序的开发时间。

For example, in the early days of Java web development, we needed to write a lot of boilerplate code to insert a record into a data source. By using the JDBCTemplate of the Spring JDBC module, we can reduce it to a few lines of code with only a few configurations.

例如,在Java Web开发的早期,我们需要编写大量的模板代码来向数据源插入一条记录。通过使用Spring JDBC模块的JDBCTemplate,我们可以将其减少到几行代码,只需进行一些配置。

3. What Is Spring Boot?

3.什么是Spring Boot?

Spring Boot is basically an extension of the Spring framework, which eliminates the boilerplate configurations required for setting up a Spring application.

Spring Boot基本上是Spring框架的一个扩展,它消除了设置Spring应用程序所需的模板配置。

It takes an opinionated view of the Spring platform, which paves the way for a faster and more efficient development ecosystem.

它对Spring平台的看法,为更快、更有效的开发生态系统铺平了道路

Here are just a few of the features in Spring Boot:

以下是Spring Boot中的一些功能。

  • Opinionated ‘starter’ dependencies to simplify the build and application configuration
  • Embedded server to avoid complexity in application deployment
  • Metrics, Health check, and externalized configuration
  • Automatic config for Spring functionality – whenever possible

Let’s get familiar with both of these frameworks step by step.

让我们一步一步地熟悉这两个框架。

4. Maven Dependencies

4.Maven的依赖性

First of all, let’s look at the minimum dependencies required to create a web application using Spring:

首先,让我们看看使用Spring创建一个Web应用程序所需的最低依赖性。

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.3.5</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.5</version>
</dependency>

Unlike Spring, Spring Boot requires only one dependency to get a web application up and running:

与Spring不同,Spring Boot只需要一个依赖关系就可以启动和运行一个Web应用。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.4.4</version>
</dependency>

All other dependencies are added automatically to the final archive during build time.

所有其他的依赖关系都会在构建时自动添加到最终存档中。

Another good example is testing libraries. We usually use the set of Spring Test, JUnit, Hamcrest, and Mockito libraries. In a Spring project, we should add all of these libraries as dependencies.

另一个很好的例子是测试库。我们通常使用Spring Test、JUnit、Hamcrest和Mockito库的集合。在Spring项目中,我们应该将所有这些库作为依赖项加入。

Alternatively, in Spring Boot we only need the starter dependency for testing to automatically include these libraries.

另外,在Spring Boot中,我们只需要测试用的启动器依赖,就可以自动包含这些库。

Spring Boot provides a number of starter dependencies for different Spring modules. Some of the most commonly used ones are:

Spring Boot为不同的Spring模块提供了一些启动依赖。一些最常用的是。

  • spring-boot-starter-data-jpa
  • spring-boot-starter-security
  • spring-boot-starter-test
  • spring-boot-starter-web
  • spring-boot-starter-thymeleaf

For the full list of starters, also check out the Spring documentation.

对于完整的启动器列表,还可以查看Spring文档

5. MVC Configuration

5.MVC配置

Let’s explore the configuration required to create a JSP web application using both Spring and Spring Boot.

让我们来探讨一下使用Spring和Spring Boot创建一个JSP网络应用程序所需的配置。

Spring requires defining the dispatcher servlet, mappings, and other supporting configurations. We can do this using either the web.xml file or an Initializer class:

Spring需要定义dispatcher servlet、映射和其他支持性配置。我们可以使用web.xml文件或Initializer类来完成。

public class MyWebAppInitializer implements WebApplicationInitializer {
 
    @Override
    public void onStartup(ServletContext container) {
        AnnotationConfigWebApplicationContext context
          = new AnnotationConfigWebApplicationContext();
        context.setConfigLocation("com.baeldung");
 
        container.addListener(new ContextLoaderListener(context));
 
        ServletRegistration.Dynamic dispatcher = container
          .addServlet("dispatcher", new DispatcherServlet(context));
         
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }
}

We also need to add the @EnableWebMvc annotation to a @Configuration class, and define a view-resolver to resolve the views returned from the controllers:

我们还需要将@EnableWebMvc注解添加到@Configuration类中,并定义一个视图解析器来解析从控制器返回的视图。

@EnableWebMvc
@Configuration
public class ClientWebConfig implements WebMvcConfigurer { 
   @Bean
   public ViewResolver viewResolver() {
      InternalResourceViewResolver bean
        = new InternalResourceViewResolver();
      bean.setViewClass(JstlView.class);
      bean.setPrefix("/WEB-INF/view/");
      bean.setSuffix(".jsp");
      return bean;
   }
}

By comparison, Spring Boot only needs a couple of properties to make things work once we add the web starter:

相比之下,Spring Boot只需要几个属性就可以在我们添加Web启动器后使事情顺利进行:

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

All of the Spring configuration above is automatically included by adding the Boot web starter through a process called auto-configuration.

上述所有的Spring配置都是通过一个名为自动配置的过程,通过添加Boot Web启动器自动包含的。

What this means is that Spring Boot will look at the dependencies, properties, and beans that exist in the application and enable configuration based on these.

这意味着Spring Boot将查看应用程序中存在的依赖关系、属性和Bean,并根据这些来启用配置。

Of course, if we want to add our own custom configuration, then the Spring Boot auto-configuration will back away.

当然,如果我们想添加自己的自定义配置,那么Spring Boot的自动配置就会退缩。

5.1. Configuring Template Engine

5.1.配置模板引擎

Now let’s learn how to configure a Thymeleaf template engine in both Spring and Spring Boot.

现在我们来学习如何在Spring和Spring Boot中配置一个Thymeleaf模板引擎。

In Spring, we need to add the thymeleaf-spring5 dependency and some configurations for the view resolver:

在Spring中,我们需要添加thymeleaf-spring5依赖性和视图解析器的一些配置。

@Configuration
@EnableWebMvc
public class MvcWebConfig implements WebMvcConfigurer {

    @Autowired
    private ApplicationContext applicationContext;

    @Bean
    public SpringResourceTemplateResolver templateResolver() {
        SpringResourceTemplateResolver templateResolver = 
          new SpringResourceTemplateResolver();
        templateResolver.setApplicationContext(applicationContext);
        templateResolver.setPrefix("/WEB-INF/views/");
        templateResolver.setSuffix(".html");
        return templateResolver;
    }

    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        templateEngine.setEnableSpringELCompiler(true);
        return templateEngine;
    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        registry.viewResolver(resolver);
    }
}

Spring Boot 1 only requires the dependency of spring-boot-starter-thymeleaf to enable Thymeleaf support in a web application. Due to the new features in Thymeleaf3.0, we also have to add thymeleaf-layout-dialect as a dependency in a Spring Boot 2 web application. Alternatively, we can choose to add a spring-boot-starter-thymeleaf dependency that’ll take care of all of this for us.

Spring Boot 1只需要依赖spring-boot-starter-thymeleaf 来在Web应用程序中启用Thymeleaf支持。由于Thymeleaf3.0的新功能,我们还必须在Spring Boot 2 Web应用程序中添加thymeleaf-layout-dialect作为依赖项。另外,我们可以选择添加一个spring-boot-starter-thymeleaf依赖项,它将为我们解决所有这些问题。

Once the dependencies are in place, we can add the templates to the src/main/resources/templates folder and the Spring Boot will display them automatically.

一旦依赖关系到位,我们就可以将模板添加到src/main/resources/templates文件夹中,Spring Boot就会自动显示这些模板。

6. Spring Security Configuration

6.Spring安全配置

For the sake of simplicity, we’ll see how the default HTTP Basic authentication is enabled using these frameworks.

为了简单起见,我们将看到如何使用这些框架启用默认的HTTP Basic认证。

Let’s start by looking at the dependencies and configuration we need to enable Security using Spring.

让我们先看看使用Spring启用安全性所需的依赖和配置。

Spring requires both the standard spring-security-web and spring-security-config dependencies to set up Security in an application.

Spring需要标准的spring-security-webspring-security-config依赖项来设置应用程序中的安全性。

Next we need to add a class that extends the WebSecurityConfigurerAdapter and makes use of the @EnableWebSecurity annotation:

接下来我们需要添加一个扩展WebSecurityConfigurerAdapter并使用@EnableWebSecurity注释的类。

@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
 
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
          .withUser("user1")
            .password(passwordEncoder()
            .encode("user1Pass"))
          .authorities("ROLE_USER");
    }
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
          .anyRequest().authenticated()
          .and()
          .httpBasic();
    }
    
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

Here we’re using inMemoryAuthentication to set up the authentication.

这里我们使用inMemoryAuthentication来设置认证。

Spring Boot also requires these dependencies to make it work, but we only need to define the dependency of spring-boot-starter-security as this will automatically add all the relevant dependencies to the classpath.

Spring Boot也需要这些依赖性才能工作,但我们只需要定义 spring-boot-starter-security的依赖性,因为这将自动将所有相关的依赖性添加到classpath。

The security configuration in Spring Boot is the same as the one above.

Spring Boot中的安全配置与上述配置相同。

To see how the JPA configuration can be achieved in both Spring and Spring Boot, we can check out our article A Guide to JPA with Spring.

要了解如何在Spring和Spring Boot中实现JPA配置,我们可以查看我们的文章A Guide to JPA with Spring

7. Application Bootstrap

7.应用Bootstrap

The basic difference in bootstrapping an application in Spring and Spring Boot lies with the servlet. Spring uses either the web.xml or SpringServletContainerInitializer as its bootstrap entry point.

在Spring和Spring Boot中引导应用程序的基本区别在于Servlet。Spring使用web.xmlSpringServletContainerInitializer作为其引导入口点。

On the other hand, Spring Boot uses only Servlet 3 features to bootstrap an application. Let’s talk about this in detail.

另一方面,Spring Boot只使用Servlet 3的功能来启动一个应用程序。让我们来详细谈谈这个问题。

7.1. How Spring Bootstraps?

7.1.Spring Bootstraps是如何实现的?

Spring supports both the legacy web.xml way of bootstrapping as well as the latest Servlet 3+ method.

Spring既支持传统的web.xml引导方式,也支持最新的Servlet 3+方式。

Let’s see the web.xml approach in steps:

让我们看看web.xml方法的步骤。

  1. Servlet container (the server) reads web.xml.
  2. The DispatcherServlet defined in the web.xml is instantiated by the container.
  3. DispatcherServlet creates WebApplicationContext by reading WEB-INF/{servletName}-servlet.xml.
  4. Finally, the DispatcherServlet registers the beans defined in the application context.

Here’s how Spring bootstraps using the Servlet 3+ approach:

下面是Spring如何使用Servlet 3+的方法进行引导。

  1. The container searches for classes implementing ServletContainerInitializer and executes.
  2. The SpringServletContainerInitializer finds all classes implementing WebApplicationInitializer.
  3. The WebApplicationInitializer creates the context with XML or @Configuration classes.
  4. The WebApplicationInitializer creates the DispatcherServlet with the previously created context.

7.2. How Spring Boot Bootstraps?

7.2.Spring Boot如何进行Bootstraps?

The entry point of a Spring Boot application is the class which is annotated with @SpringBootApplication:

Spring Boot应用程序的入口是被注解为@SpringBootApplication的类:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

By default, Spring Boot uses an embedded container to run the application. In this case, Spring Boot uses the public static void main entry point to launch an embedded web server.

默认情况下,Spring Boot使用一个嵌入式容器来运行应用程序。在这种情况下,Spring Boot使用public static void main入口点来启动一个嵌入式Web服务器。

It also takes care of the binding of the Servlet, Filter, and ServletContextInitializer beans from the application context to the embedded servlet container.

它还负责将Servlet、FilterServletContextInitializer Bean从应用上下文绑定到嵌入式Servlet容器。

Another feature of Spring Boot is that it automatically scans all the classes in the same package or sub packages of the Main-class for components.

Spring Boot的另一个特点是,它会自动扫描Main-class的同一包或子包中的所有类,以寻找组件。

Additionally, Spring Boot provides the option of deploying it as a web archive in an external container. In this case, we have to extend the SpringBootServletInitializer:

此外,Spring Boot还提供了将其作为Web归档文件部署到外部容器的选项。在这种情况下,我们必须扩展SpringBootServletInitializer

@SpringBootApplication
public class Application extends SpringBootServletInitializer {
    // ...
}

Here the external servlet container looks for the Main-class defined in the META-INF file of the web archive, and the SpringBootServletInitializer will take care of binding the Servlet, Filter, and ServletContextInitializer.

在这里,外部Servlet容器寻找Web存档的META-INF文件中定义的Main类,而SpringBootServletInitializer将负责绑定Servlet、Filter、ServletContextInitializer。

8. Packaging and Deployment

8.包装和部署

Finally, let’s see how an application can be packaged and deployed. Both of these frameworks support common package managing technologies like Maven and Gradle; however, when it comes to deployment, these frameworks differ a lot.

最后,让我们看看如何打包和部署一个应用程序。这两个框架都支持常见的包管理技术,如Maven和Gradle;然而,当涉及到部署时,这些框架有很大的不同。

For instance, the Spring Boot Maven Plugin provides Spring Boot support in Maven. It also allows packaging executable jar or war archives and running an application “in-place.”

例如,Spring Boot Maven Plugin在Maven中提供Spring Boot支持。它还允许打包可执行的jar或war档案,并 “就地 “运行一个应用程序。

Some of the advantages of Spring Boot over Spring in the context of deployment include:

在部署方面,Spring Boot比Spring的一些优势包括。

  • Provides embedded container support
  • Provision to run the jars independently using the command java -jar
  • Option to exclude dependencies to avoid potential jar conflicts when deploying in an external container
  • Option to specify active profiles when deploying
  • Random port generation for integration tests

9. Conclusion

9.结论

In this article, we learned about the differences between Spring and Spring Boot.

在这篇文章中,我们了解了Spring和Spring Boot的区别。

In a few words, we can say that Spring Boot is simply an extension of Spring itself to make development, testing, and deployment more convenient.

用几句话来说,我们可以说Spring Boot只是Spring本身的一个扩展,使开发、测试和部署更加方便。