Spring与SpringBoot 对比 不同 A Comparison Between Spring and Spring Boot

原文链接:A Comparison Between Spring and Spring Boot

1. Overview 概述

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

在这篇文章中,来看一看标准的Spring框架和SpringBoot的不同之处吧

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.

让我们来看看一些模块,如MVC和Security,在Spring中使用和SpringBoot中使用的不同之处吧

2. What Is Spring? 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框架封装了一些很不错的功能,像依赖注入,还有一些开箱即用的模块,如:

  • 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.

例如,在以前的WEB应用开发中,开发人员需要写很多大致相同的冗余代码来插入一条记录到数据库。而通过使用SpringJDBC模块中的JDBCTemplate,仅输编写几行代码就可以实现了,需要做的就是一些配置罢了。

3. What Is Spring Boot? 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 Boot 以Spring框架为基石,它致力于打造一个快速高效的Spring开发生态系统。

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

以下列出少数几个Spring Boot 的特色功能:

  • Opinionated ‘starter' dependencies to simplify the build and application configuration 以 starter 为主要依据添加依赖,以此来简化繁琐的程序配置
  • Embedded server to avoid complexity in application deployment 内嵌服务应用来避免应用部署过程中的复杂配置
  • Metrics, Health check, and externalized configuration 数据监测、运行状况监测及外部配置文件加载等
  • Automatic config for Spring functionality – whenever possible 自动和Spring功能相协调?

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

来一步一步的熟悉这俩吧

4. Maven Dependencies 添加Maven依赖引入Spring[Boot]

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:

SpringBoot不像Spring那样,它只需要添加一个依赖即可实现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框架中,我们要添加一堆依赖,如Spring Test,Junit,Hamcrest和 Mockito

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

而在SpringBoot中,仅需要添加测试的Starter即可完成测试框架库的添加

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

SpringBoot也准备了一堆的Starter对就了不同的Spring模块,方便使用添加,以下是最常用的一些

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

5. MVC Configuration MVC的配置

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

接下来看看在Spring框架和SpringBoot中如何创建一个JSP的WEB应用程序吧

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框架要求开发人员定义Servlet Mapping 等一些其它配置,可以在web.xml中配置或初始化类来设置这些

// 自定义WEB应用程序初始化类
public class MyWebAppInitializer implements WebApplicationInitializer {
 
    // WEB应用启用的回调
    @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:

相比之下,一旦我们添加了WEB的Starter依赖,SpringBoot仅需几个属性配置即可开始开发工作了

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框架配置项,在SpringBoot中,只要添加了web,就会被名为auto-configuration的机制来为应用自动添加配置

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.

什么意思呢?意思就是SpringBoot将会找寻应用程序中的这些配置并自动加载设置这些属性。

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

当然,要是我们添加自己的配置,就会覆盖SpringBoot的自动配置(即SpringBoot的自动配置失效)

5.1. Configuring Template Engine 配置视图模块引擎

Now let's learn how to configure a Thymeleaf template engine in both Spring and 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;
    }

    // 配置注册 Thymeleaf 解析器
    @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.

SpringBoot 1.*版本仅需要添加 spring-boot-starter-thymeleaf 依赖即可,而在 SpringBoot 2.*版本中,由于Thymeleaf3 的新我,需要另外添加 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 目录中,Sp日你哥Boot就会自动解析展示它们。

6. Spring Security Configuration Spring的安全模块配置

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

简单至上,来看看默认的HTTP验证是如何在这两个里面配置的吧

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-web 和 spring-security-config 依赖来为应用程序添加安全模块。

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

接着需要做的是,添加一个 WebSecurityConfigurerAdapter 的子类,并使用 @EnableWebSecurity 注解标记为配置类

// WEB应用安全模块配置类
@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.

这里使用的 固定用户验证 (运行时保存在运行内存中,编写在代码中)

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.

SpringBoot也需要这些依赖来使用安全模块,但是呢,只需添加 spring-boot-starter-security 的依赖,它自动就添加相关的额外依赖了。

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

SpringBoot安全模块所需的配置与上面Spring的相同

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.

通过这篇 ”A Guide to JPA with Spring“ 可以学习下如何在Spring框架和SpringBoot中如用JPA。

7. Application 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.

在启动程序的最根本的不同之处在于Servlet。其中,Spring框架使用的要么是 web.xml 文件,要么是 SpringServletContainerInitializer 初始化类作为程序入口。

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

而SpringBoot则是使用 Servlet3 的特性来启动程序,接下来细细讲

7.1. How Spring Bootstraps? Spring应用程序启动

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

Spring框架支持传统的web.xml方式启动程序,也支持 Servlet3 之后的方式来启动程序。

Let's see the web.xml approach in steps: 使用web.xml配置启动程序的步骤:

  1. Servlet container (the server) reads web.xml. Servlet容器(Server)读取web.xml配置文件
  2. The DispatcherServlet defined in the web.xml is instantiated by the container. 在 web.xml 中定义的 DispatcherServlet 类实例被容器初始化
  3. DispatcherServlet creates WebApplicationContext by reading WEB-INF/{servletName}-servlet.xml. 接着使用 DispatcherServlet 读取 *-servlet.xml 后创建 WebApplicationContext
  4. Finally, the DispatcherServlet registers the beans defined in the application context. 最后在应用程序上下文环境中注册一系列的Bean

Here's how Spring bootstraps using the Servlet 3+ approach: Servelt3的方式启动程序步骤:

  1. The container searches for classes implementing ServletContainerInitializer and executes. 容器搜寻接口 ServletContainerInitializer 的所有实现类并调用执行来初始化相应配置
  2. The SpringServletContainerInitializer finds all classes implementing WebApplicationInitializer. 之后再搜寻 WebApplicationInitializer 的所有实现类
  3. The WebApplicationInitializer creates the context with XML or @Configuration classes. 接着是 WebApplicationInitializer 的实例通过读取 XML 或使用 @Configuration 注解标记的配置类来创建上下文环境
  4. The WebApplicationInitializer creates the DispatcherServlet with the previously created context. 最后使用上面创建上下文环境来创建 DispatcherServlet 实例

7.2. How Spring Boot Bootstraps? SpringBoot应用程序启动

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

SpringBoot程序的入口是一个使用 @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.

通常情况下,SpringBoot使用内嵌的服务应用来启动程序,它使用启动类的main方法来作为程序入口点来启动程序

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

程序入口类之后也会在程序上下文和内嵌的服务容器中绑定注册 Servlet Filter 和 ServletContextInitializer 

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.

SpringBoot的另一特点是它会扫描主入口类同级或子级的类包,去扫描所有配置类

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:

除此之外,SpringBoot可以把应用程序打包并发布到外部的服务应用容器中。如果是这样,则需要继承 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.

有了以上的这个子类,外部的服务应用容器会搜索 META-INF 文件中定义的 Main-class 属性,调用执行以此来初始化绑定 Servlet Filter 及 ServletContextInitializer

 

 

8. Packaging and Deployment 打包部署发布

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.

最后呢,来看看如何打包及发布一个应用程序吧。Spring与SpringBoot都支持像 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.”

举例来说,SpringBoot Maven插件可以把应用程序打包为 可执行的Jar文件 或 WAR包,并且单独的可以支行 Jar包型的应用程序。

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

SpringBoot在发布方面相较于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 最后

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

这篇文章中分析了Spring与SpringBoot的一些不同之处。

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.

简单来说,SpringBoot就是Spring框架的一个扩展件,来简化开发、测试及部署。

大家关注点赞哈

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值