3年前 (2021-03-31)  相关技术 |   抢沙发  339 
文章评分 0 次,平均分 0.0

Spring框架和SpringBoot之间的区别

在本教程中,我们将研究标准Spring框架和Spring Boot之间的区别。

我们将重点讨论Spring的模块,如MVCSecurity,在核心Spring中使用时与在Boot中使用时的区别。

Spring是什么?

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

它包含了一些很好的功能,比如依赖注入,以及一些现成的模块,比如:

这些模块可以大大缩短应用程序的开发时间。

例如,在java web开发的早期,我们需要编写大量样板代码来将记录插入到数据源中。通过使用springjdbc模块的JDBCTemplate,我们可以用很少的配置将它简化为几行代码。

Spring Boot是什么?

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

它对Spring平台持固执己见的观点,它为更快、更高效的开发生态系统铺平了道路。

以下是Spring Boot的一些功能:

  • 持约定优于配置的“starter”依赖关系,以简化构建和应用程序配置
  • 嵌入式服务器避免了应用程序部署的复杂性
  • 度量、运行状况检查和外部化配置
  • 自动配置-只要可能

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

Maven依赖项

首先,让我们看看使用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>

与Spring不同,Spring Boot只需要一个依赖项即可启动并运行web应用程序:

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

在构建期间,所有其他依赖项都会自动添加到最终存档中。

另一个很好的例子是测试库。我们通常使用一组Spring-TestJUnitHamcrestMockito库。在Spring项目中,我们应该添加所有这些库作为依赖项。

或者,在springboot中,我们只需要starter依赖项就可以自动包含这些库。

springboot为不同的Spring模块提供了许多启动程序依赖项。最常用的方法有:

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

要获得starters的完整列表,还可以查看Spring文档:https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-starter

MVC配置

让我们研究一下使用Spring和SpringBoot创建jsp web应用程序所需的配置。

Spring需要定义dispatcherservlet、映射和其他支持配置。我们可以用web.xml文件或初始值设定项类:

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("/");
    }
}

我们还需要将@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;
   }
}

相比之下,在添加web starter后,Spring Boot只需要几个属性就可以工作:

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

通过一个名为auto-configurationprocess添加bootwebstarter,上面所有的Spring配置都会自动包含进来。

这意味着springboot将查看应用程序中存在的依赖项、属性和bean,并基于它们启用配置。

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

配置模板引擎

现在让我们学习如何在Spring和springboot中配置Thymeleaf模板引擎。

在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);
    }
}

SpringBoot只需要springbootstarter thymeleaf的依赖性就可以在web应用程序中启用thymeleaf支持。由于Thymeleaf3.0中的新特性,我们还必须在springboot2web应用程序中添加thymeleaf-layout-dialect作为依赖项。或者,我们可以选择添加一个springbootstarter和eleaf依赖,它将为我们处理所有这些。

一旦依赖项就位,我们就可以将模板添加到src/main/resources/templates文件夹中,Spring引导将自动显示它们。

Spring Security 配置

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

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

Spring需要标准的springsecuritywebspringsecurityconfig依赖项来设置应用程序中的安全性。

接下来,我们需要添加一个类来扩展WebSecurityConfigureAdapter并使用@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();
    }
}

这里我们使用inMemoryAuthentication来设置身份验证。

springboot还需要这些依赖项才能工作,但是我们只需要定义spring-boot-starter-security的依赖项,因为这样会自动将所有相关的依赖项添加到classpath类路径中。

springboot中的security安全配置与上面的相同。

要了解如何在Spring和Spring引导中实现JPA配置,我们可以查看我们的文章A Guide To JPA with Spring:https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa

Application Bootstrap

在Spring和Spring引导中引导应用程序的基本区别在于servlet。Spring使用web.xml或SpringServletContainerInitializer作为其引导入口点。

另一方面,SpringBoot只使用Servlet3特性来引导应用程序。我们来详细谈谈。

Spring如何引导?

Spring既支持传统的web.xml引导方式以及最新的Servlet3+方法。

让我们看看web.xml分步进近:

1. Servlet容器(服务器)读取web.xml.

2.DispatcherServlet定义在web.xml中由容器实例化。

3. DispatcherServlet通过读取WEB-INF/{servletName}创建WebApplicationContext-servlet.xml.

4. 最后,DispatcherServlet注册在应用程序上下文中定义的bean。

下面是如何使用Servlet3+方法进行Spring引导:

1. 容器搜索实现ServletContainerInitializer的类并执行。

2. SpringServletContainerInitializer查找实现WebApplicationInitializer的所有类。

3. WebApplicationInitializer使用XML或@Configuration类创建上下文。

4. WebApplicationInitializer使用先前创建的上下文创建DispatcherServlet

如何启动Spring Boot?

Spring Boot应用程序的入口点是用@SpringBootApplication注释的类:

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

默认情况下,springboot使用嵌入式容器来运行应用程序。在本例中,springboot使用public static void主入口点来启动嵌入式web服务器。

它还负责将ServletFilterservletContextInitializerbean从应用程序上下文绑定到嵌入式Servlet容器。

springboot的另一个特性是,它自动扫描主类的同一个包或子包中的所有类中的组件。

此外,springboot还提供了将其部署为外部容器中的web存档的选项。在这种情况下,我们必须扩展SpringBootServletInitializer

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

在这里,外部servlet容器查找在web存档的META-INF文件中定义的主类,SpringBootServletInitializer将负责绑定servlet、过滤器和ServletContextInitializer

打包和部署

最后,让我们看看如何打包和部署应用程序。这两个框架都支持Maven和Gradle等常见的包管理技术;但是,在部署方面,这些框架有很大的不同。

例如,springboot maven插件在Maven中提供springboot支持。它还允许打包可执行jar或war,并“就地”运行应用程序

在部署环境中,Spring Boot优于Spring的一些优点包括:

  • 提供嵌入式容器支持
  • 设置为使用命令java-jar独立运行jar
  • 用于排除依赖项的选项,以避免在外部容器中部署时发生潜在的jar冲突
  • 用于在部署时指定活动配置文件的选项
  • 集成测试的随机端口生成

结论

在本文中,我们了解了Spring和Spring Boot之间的区别。

简而言之,我们可以说springboot只是Spring本身的一个扩展,它使开发、测试和部署更加方便。

 

除特别注明外,本站所有文章均为老K的Java博客原创,转载请注明出处来自https://javakk.com/1776.html

关于

发表评论

表情 格式

暂无评论

登录

忘记密码 ?

切换登录

注册