作者:乐傻驴 uee.me/cNDC8

概述

对于 SpringSpringBoot到底有什么区别,我听到了很多答案,刚开始迈入学习 SpringBoot的我当时也是一头雾水,随着经验的积累、我慢慢理解了这两个框架到底有什么区别,相信对于用了 SpringBoot很久的同学来说,还不是很理解 SpringBoot到底和 Spring有什么区别,看完文章中的比较,或许你有了不同的答案和看法!

什么是Spring

作为 Java开发人员,大家都 Spring都不陌生,简而言之, Spring框架为开发 Java应用程序提供了全面的基础架构支持。它包含一些很好的功能,如依赖注入和开箱即用的模块,如:

SpringJDBC、SpringMVC、SpringSecurity、SpringAOP、SpringORM、SpringTest,这些模块缩短应用程序的开发时间,提高了应用开发的效率例如,在 JavaWeb开发的早期阶段,我们需要编写大量的代码来将记录插入到数据库中。但是通过使用 SpringJDBC模块的 JDBCTemplate,我们可以将操作简化为几行代码。

什么是Spring Boot

SpringBoot基本上是 Spring框架的扩展,它消除了设置 Spring应用程序所需的 XML配置,为更快,更高效的开发生态系统铺平了道路。

SpringBoot中的一些特征:

1、创建独立的 Spring应用。
2、嵌入式 TomcatJettyUndertow容器(无需部署war文件)。
3、提供的 starters 简化构建配置
4、尽可能自动配置 spring应用。
5、提供生产指标,例如指标、健壮检查和外部化配置
6、完全没有代码生成和 XML配置要求

从配置分析

Maven依赖

首先,让我们看一下使用Spring创建Web应用程序所需的最小依赖项

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

与Spring不同,Spring Boot只需要一个依赖项来启动和运行Web应用程序:

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

在进行构建期间,所有其他依赖项将自动添加到项目中。

另一个很好的例子就是测试库。我们通常使用 SpringTestJUnitHamcrestMockito库。在 Spring项目中,我们应该将所有这些库添加为依赖项。但是在 SpringBoot中,我们只需要添加 spring-boot-starter-test依赖项来自动包含这些库。

Spring Boot为不同的Spring模块提供了许多依赖项。一些最常用的是:

spring-boot-starter-data-jpaspring-boot-starter-securityspring-boot-starter-testspring-boot-starter-webspring-boot-starter-thymeleaf

有关 starter的完整列表,请查看Spring文档。

MVC配置

让我们来看一下 SpringSpringBoot创建 JSPWeb应用程序所需的配置。

Spring需要定义调度程序 servlet,映射和其他支持配置。我们可以使用 web.xml 文件或 Initializer类来完成此操作:

public class MyWebAppInitializer implements WebApplicationInitializer {@Overridepublic void onStartup(ServletContext container) {AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();context.setConfigLocation("com.pingfangushi");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 { @Beanpublic ViewResolver viewResolver() {InternalResourceViewResolver bean= new InternalResourceViewResolver();bean.setViewClass(JstlView.class);bean.setPrefix("/WEB-INF/view/");bean.setSuffix(".jsp");return bean;}
}

再来看 SpringBoot一旦我们添加了 Web启动程序, SpringBoot只需要在 application配置文件中配置几个属性来完成如上操作:

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

上面的所有Spring配置都是通过一个名为auto-configuration的过程添加 Bootweb starter来自动包含的。

这意味着 SpringBoot将查看应用程序中存在的依赖项,属性和 bean,并根据这些依赖项,对属性和 bean进行配置。当然,如果我们想要添加自己的自定义配置,那么 SpringBoot自动配置将会退回。

配置模板引擎

现在我们来看下如何在Spring和Spring Boot中配置Thymeleaf模板引擎。

Spring中,我们需要为视图解析器添加 thymeleaf-spring5依赖项和一些配置:

@Configuration
@EnableWebMvc
public class MvcWebConfig implements WebMvcConfigurer {@Autowiredprivate ApplicationContext applicationContext;@Beanpublic SpringResourceTemplateResolver templateResolver() {SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();templateResolver.setApplicationContext(applicationContext);templateResolver.setPrefix("/WEB-INF/views/");templateResolver.setSuffix(".html");return templateResolver;}@Beanpublic SpringTemplateEngine templateEngine() {SpringTemplateEngine templateEngine = new SpringTemplateEngine();templateEngine.setTemplateResolver(templateResolver());templateEngine.setEnableSpringELCompiler(true);return templateEngine;}@Overridepublic void configureViewResolvers(ViewResolverRegistry registry) {ThymeleafViewResolver resolver = new ThymeleafViewResolver();resolver.setTemplateEngine(templateEngine());registry.viewResolver(resolver);}
}

SpringBoot1X只需要 spring-boot-starter-thymeleaf的依赖项来启用 Web应用程序中的 Thymeleaf支持。  但是由于 Thymeleaf3.0中的新功能,我们必须将 thymeleaf-layout-dialect 添加为 SpringBoot2XWeb应用程序中的依赖项。配置好依赖,我们就可以将模板添加到 src/main/resources/templates文件夹中, SpringBoot将自动显示它们。

Spring Security 配置

为简单起见,我们使用框架默认的 HTTPBasic身份验证。让我们首先看一下使用 Spring启用 Security所需的依赖关系和配置。

Spring首先需要依赖 spring-security-webspring-security-config 模块。接下来, 我们需要添加一个扩展 WebSecurityConfigurerAdapter的类,并使用 @EnableWebSecurity注解:

@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("admin").password(passwordEncoder().encode("password")).authorities("ROLE_ADMIN");}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().httpBasic();}@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}
}

这里我们使用 inMemoryAuthentication来设置身份验证。同样, SpringBoot也需要这些依赖项才能使其工作。但是我们只需要定义 spring-boot-starter-security的依赖关系,因为这会自动将所有相关的依赖项添加到类路径中。

SpringBoot中的安全配置与上面的相同

应用程序启动引导配置

SpringSpringBoot中应用程序引导的基本区别在于 servletSpring使用 web.xmlSpringServletContainerInitializer作为其引导入口点。SpringBoot仅使用 Servlet3功能来引导应用程序,下面让我们详细来了解下

Spring 引导配置

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

配置 web.xml方法启动的步骤

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

web.xml中定义的 DispatcherServlet由容器实例化

DispatcherServlet通过读取 WEB-INF/{servletName}-servlet.xml来创建 WebApplicationContext。最后, DispatcherServlet注册在应用程序上下文中定义的 bean

使用 Servlet3+方法的 Spring启动步骤

容器搜索实现 ServletContainerInitializer的类并执行 SpringServletContainerInitializer找到实现所有类 WebApplicationInitializer``WebApplicationInitializer创建具有XML或上下文 @ConfigurationWebApplicationInitializer创建 DispatcherServlet与先前创建的上下文。

SpringBoot 引导配置

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

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

默认情况下, SpringBoot使用嵌入式容器来运行应用程序。在这种情况下, SpringBoot使用 publicstaticvoidmain入口点来启动嵌入式 Web服务器。此外,它还负责将 ServletFilterServletContextInitializerbean从应用程序上下文绑定到嵌入式 servlet容器。SpringBoot的另一个特性是它会自动扫描同一个包中的所有类或 Main类的子包中的组件。

SpringBoot提供了将其部署到外部容器的方式。我们只需要扩展 SpringBootServletInitializer即可:

/*** War部署** @author SanLi* Created by 2689170096@qq.com on 2018/4/15*/
public class ServletInitializer extends SpringBootServletInitializer {@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder application) {return application.sources(Application.class);}@Overridepublic void onStartup(ServletContext servletContext) throws ServletException {super.onStartup(servletContext);servletContext.addListener(new HttpSessionEventPublisher());}
}

这里外部 servlet容器查找在war包下的 META-INF文件夹下MANIFEST.MF文件中定义的 Main-classSpringBootServletInitializer将负责绑定 ServletFilterServletContextInitializer

打包和部署

最后,让我们看看如何打包和部署应用程序。这两个框架都支持 MavenGradle等通用包管理技术。但是在部署方面,这些框架差异很大。例如,Spring Boot Maven插件在 Maven中提供 SpringBoot支持。它还允许打包可执行 jarwar包并 就地运行应用程序。

在部署环境中 SpringBoot 对比 Spring的一些优点包括:

1、提供嵌入式容器支持
2、使用命令java -jar独立运行jar
3、在外部容器中部署时,可以选择排除依赖关系以避免潜在的jar冲突
4、部署时灵活指定配置文件的选项
5、用于集成测试的随机端口生成

结论

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

特别推荐一个分享架构+算法的优质内容,还没关注的小伙伴,可以长按关注一下:

长按订阅更多精彩▼如有收获,点个在看,诚挚感谢

Spring 和 SpringBoot 最核心的 3 大区别,详解!相关推荐

  1. 以HANA为核心 SAP实时数据平台详解

    文章讲的是以HANA为核心 SAP实时数据平台详解,在收购Sybase之前,SAP还不算是个数据库厂商,但其在ERP市场的地位举足轻重.那时的SAP只能通过与其他厂商合作来满足其商务套件的数据库需求, ...

  2. Spring Boot 整合 shiro 之盐值加密认证详解(六)

    Spring Boot 整合 shiro 之盐值加密认证详解 概述 不加盐认证 加入密码认证核心代码 修改 CustomRealm 新增获取密文的方法 修改 doGetAuthenticationIn ...

  3. 【夯实Spring Cloud】Spring Cloud中的Eureka服务注册与发现详解

    本文属于[夯实Spring Cloud]系列文章,该系列旨在用通俗易懂的语言,带大家了解和学习Spring Cloud技术,希望能给读者带来一些干货.系列目录如下: [夯实Spring Cloud]D ...

  4. “戏”说Spark-Spark核心-RDD转换操作算子详解(一)

    "戏"说Spark-Spark核心-RDD转换行动类算子详解 算子概述 对于RDD可以有两种计算方式: 转换(返回值还是一个RDD)---懒执行 操作(返回值不是一个RDD)--- ...

  5. 十大排序详解(java实现)

    十大排序详解(java实现) 一.十大排序算法概述 1.定义 2.分类 3.比较 4.相关概念 二.各算法原理及实现 1.冒泡排序 2.简单选择排序(Selection Sort) 3.直接插入排序( ...

  6. java中属性文件读取案例_java相关:Spring中属性文件properties的读取与使用详解

    java相关:Spring中属性文件properties的读取与使用详解 发布于 2020-6-3| 复制链接 摘记: Spring中属性文件properties的读取与使用详解实际项目中,通常将一些 ...

  7. Spring Cloud Eureka 入门 (三)服务消费者详解

    2019独角兽企业重金招聘Python工程师标准>>> 摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! "真正的进步 ...

  8. SpringBoot——slf4j+logback日志处理及配置详解

    SpringBoot--sl4j+logback日志处理及配置详解 日志的级别 打印级别:ALL > TRACE > FATAL > DEBUG > INFO > WAR ...

  9. php 表单提交文件大小,PHP如何通过表单直接提交大文件详解

    PHP如何通过表单直接提交大文件详解 前言 我想通过表单直接提交大文件,django 那边我就是这么干的.而对于 php 来说,我认为尽管可以设置最大上传的大小,但最大也无法超过内存大小,因为它无法把 ...

最新文章

  1. Swift 闭包表达式
  2. 开源全能播放器Vitamio的使用
  3. MyBatis源码-深入理解MyBatis Executor的设计思想
  4. JavaScript基础:(加号,数值转换,布尔转换)
  5. Java编程技巧:如何实现参数的输入输出?
  6. kubectl logs -f tail 显示100_系统管理员应该知道的9个kubectl命令
  7. java序列化流_java 序列化流与反序列化流
  8. TensorFlow——实现线性回归算法
  9. 调研分析:全球与中国乙氧呋草黄市场现状及未来发展趋势
  10. int i=-20; unsigned int j = 10; i+j;的问题
  11. 初学键盘计算机输入时注意,打字练习说明.doc
  12. 【Unity技术积累】人物移动 坦克式移动 WASD 动画
  13. Dell PowerEdge全系服务器RAID卡驱动程序 下载地址
  14. 网络毕业设计--基于华为ensp防火墙双出口负载拟真实验
  15. [Pytorch框架] 5.2 Pytorch处理结构化数据
  16. oracle按非选列排序,如何选择和排序不在Groupy中的列按SQL语句 – Oracle
  17. Swift学习之闭包
  18. 微信昵称表情符号前端显示问题
  19. 【读书】马克·李维《自由的孩子》摘录
  20. js基础之探秘Array的原型方法

热门文章

  1. JavaScript 中 call、apply和bind的用法区别
  2. android京东秒杀倒计时,js实现京东秒杀倒计时功能
  3. win8计算机安全模式,安全模式,教您Win8怎么进入安全模式
  4. centeros7网络服务无法启动_Linux网络服务02——DHCP原理与配置
  5. virtualbox 创建桥接网络_VirtualBox桥接网络的简单配置,让虚拟机直接访问网络
  6. c语言一个偶数用两个素数表示,用java怎样编写一个偶数总能表示为两个素数之和的程序...
  7. Codeforces Round #703 (Div. 2)(A ~ F)超高质量题解【每日亿题2 / 19】
  8. ACM 全部算法总结
  9. java预处理指令region_VS #region
  10. React Native 初体验