Chapter 1: SpringBoot入门
创始人
2024-06-02 07:05:17
0

尚硅谷SpringBoot顶尖教程

1. SpringBoot简介

SpringBoot用来简化Spring应用开发, 约定大于配置, 去繁从简, just run就能创建一个独立的、产品级的应用。

背景:

J2EE笨重的开发,繁多的配置,低下的开发效率,复杂的部署流程, 第三方技术集成难度大。

解决:

spring全家桶时代。

SpringBoot ➡ J2EE一站式解决方案。

SpringCloud ➡ 分布式整体解决方案。

优点:

  • 快速创建独立运行的Spring项目以及与主流框架集成;
  • 使用嵌入式的Servlet容器,应用无需打成WAR包;
  • starters起步依赖与版本控制;
  • 大量的自动配置, 简化开发; 也可以修改默认值;
  • 无需配置XML, 无代码生成, 开箱即用。
  • 准生产环境的运行时应用监控;

总结:

  • 简化Spring应用开发的一个脚手架;
  • 整个Spring技术栈的大整合;
  • JavaEE开发的一站式解决方案;

2. 微服务

2014年 , Martin Fowler 提出了微服务化的思想.

一个应用是一组小型服务, 通过HTTP进行通信;每一个功能元素最终都是一个可独立替换和独立升级的软件单元。

3. 环境准备

jdk1.8:spring boot 1.7及以上

maven3.x: maven3.3及以上

IntelliJ IDEA 2019.3.4 x64或Eclipse集成STS插件

springBoot 1.5.9.REALEASE

3.1 Maven设置

给maven的settings.xml配置文件的profiles标签指定jdk版本。

   jdk1.8       true    1.8          1.8    1.8    1.8      
 

设置Maven仓库的远程仓库地址, 用来从远程下载依赖, 可配置多个, 第一个下载不到可以往下面继续寻找.

alimavencentralaliyun mavenhttp://maven.aliyun.com/nexus/content/repositories/central/nexus-aliyuncentralNexus aliyunhttp://maven.aliyun.com/nexus/content/groups/publiccentralMaven Repository Switchboardhttp://repo1.maven.org/maven2/centralrepo2centralHuman Readable Name for this Mirror.http://repo2.maven.org/maven2/ibibliocentralHuman Readable Name for this Mirror.http://mirrors.ibiblio.org/pub/mirrors/maven2/jboss-public-repository-groupcentralJBoss Public Repository Grouphttp://repository.jboss.org/nexus/content/groups/public

3.2 Idea设置

在idea中配置maven, 指定maven的安装目录、settings.xml文件位置; 以及maven本地仓库的目录;
在这里插入图片描述

4. HelloWorld案例

需求:浏览器发送hello请求,服务器接受请求并处理,响应Hello World字符串。

创建maven工程, 导入SpringBoot依赖。


4.0.0	org.springframework.bootspring-boot-starter-parent1.5.10.RELEASE com.atguguispring-boot-01-hello-quick0.0.1-SNAPSHOTwarspring-boot-01-hello-quickDemo project for Spring Boot1.8org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-maven-plugin

编写主启动类.

package com.atgugui;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication // 用来标注一个主程序类,说明这是一个springboot应用
public class HelloWorldMainApplication {public static void main(String[] args) {SpringApplication.run(HelloWorldMainApplication.class, args);}
}

编写Controller

@RestController
//@Controller
public class HelloController {//    @ResponseBody@RequestMapping("/hello")public String hello() {return "Hello World";}
}

运行主程序, 测试.

windows环境使用命令mvn spring-boot:run启动程序,也可以使用开发工具启动。
在这里插入图片描述
或者
在这里插入图片描述

启动标识:
在这里插入图片描述
在这里插入图片描述
启动了内嵌的tomcat的8080端口,http端口。
在这里插入图片描述
也可以将这个应用打成jar包,直接使用java -jar命令启动应用包。
在这里插入图片描述
java -jar spring-boot-01-helloworld-1.0-SNAPSHOT.jar

在这里插入图片描述

5. pom.xml

5.1 SpringBoot应用父项目

SpringBoot项目的pom.xml中导入了父项目spring-boot-starter-parent

org.springframework.bootspring-boot-starter-parent1.5.10.RELEASE 

它的父项目是:

org.springframework.bootspring-boot-dependencies1.5.10.RELEASE../../spring-boot-dependencies

spring-boot-dependencies中来真正管理spring boot应用里面的所有依赖版本。

Spring Boot的版本管理中心,我们以后导入依赖默认是不需要写版本;如果没有在dependencies里面管理的依赖是需要我们自己写版本号的。
在这里插入图片描述

5.2 起步依赖

org.springframework.bootspring-boot-starter-web

spring-boot-starter-web:

spring-boot-starter:springboot的场景启动器,帮助我们导入了web模块正常运行所依赖的组件。

SpringBoot将所有的功能场景都抽取出来,做成一个个的starter启动器,只需要在项目里面引入这些starter,相关场景的所有依赖都会导入进来。要用什么功能就导入什么场景的启动器 , 实现按需引入。

6. 主启动类

6.1 @SpringBootApplication

主启动类是SpringBoot应用的程序入口。

@SpringBootApplication:springboot应用标注在某个类上说明这个类是SpringBoot的主配置类,通过运行这个类的main方法来启动SpringBoot应用。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {//....
}

@SpringBootConfiguration:标注在某个类上,表示这是一个SpringBoot的配置类。

​ @Configuration:配置类上来标注这个注解。配置类替换原来的配置文件。

配置类也是容器中的一个组件. @Component

6.2 @EnableAutoConfiguration

@EnableAutoConfiguration: 开启自动配置功能,以前我们需要配置的内容,SpringBoot帮助我们自动配置。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {//...
}    

@AutoConfigurationPackage:自动配置包

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {
}

@Import({AutoConfigurationPackages.Registrar.class}) : Spring的底层注解@Import,给容器中导入一个组件,导入的组件是AutoConfigurationPackages.Registrar.class, 实现了将主配置类(@SpringBootApplication标注的类)所在包及下面所有子包里面的所有组件扫描到Spring容器中。

@Order(Ordered.HIGHEST_PRECEDENCE)
static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {@Overridepublic void registerBeanDefinitions(AnnotationMetadata metadata,BeanDefinitionRegistry registry) {// 在这行打断点,启动应用调试; 下面执行结果是当前应用主启动类所以的包名register(registry, new PackageImport(metadata).getPackageName());}@Overridepublic Set determineImports(AnnotationMetadata metadata) {return Collections.singleton(new PackageImport(metadata));}
}
 

在这里插入图片描述

6.3 @Import

@Import({EnableAutoConfigurationImportSelector.class}) :给容器中导入组件。

EnableAutoConfigurationImportSelector:导入所需要组件的选择器。

将所有需要导入的组件以全类名的方式返回,这些组件就会被添加到容器中。

会给容器中导入自动配置类(xxxAutoConfiguration),就是给容器中导入这个场景需要的所有组件,并配置好这些组件。

AutoConfigurationImportSelector#selectImports

public class AutoConfigurationImportSelectorimplements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware,BeanFactoryAware, EnvironmentAware, Ordered {// ....@Overridepublic String[] selectImports(AnnotationMetadata annotationMetadata) {if (!isEnabled(annotationMetadata)) {return NO_IMPORTS;}try {AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);AnnotationAttributes attributes = getAttributes(annotationMetadata);// 返回所有自动配置类的全路径名List configurations = getCandidateConfigurations(annotationMetadata,attributes);configurations = removeDuplicates(configurations);configurations = sort(configurations, autoConfigurationMetadata);Set exclusions = getExclusions(annotationMetadata, attributes);checkExcludedClasses(configurations, exclusions);configurations.removeAll(exclusions);configurations = filter(configurations, autoConfigurationMetadata);fireAutoConfigurationImportEvents(configurations, exclusions);return configurations.toArray(new String[configurations.size()]);}catch (IOException ex) {throw new IllegalStateException(ex);}}
}

在这里插入图片描述
有了自动配置类,免去了我们手动编写配置注入功能组件等工作。

AutoConfigurationImportSelector#getCandidateConfigurations

// SpringFactoriesLoader.loadFactoryNames(...)
protected List getCandidateConfigurations(AnnotationMetadata metadata,AnnotationAttributes attributes) {List configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());Assert.notEmpty(configurations,"No auto configuration classes found in META-INF/spring.factories. If you "+ "are using a custom packaging, make sure that file is correct.");return configurations;
}

SpringFactoriesLoader#loadFactoryNames

SpringBoot在启动的时候从类路径下的META-INF/spring.factories中获取EnableAutoConfiguration指定的值,将这些值作为自动配置类导入到容器中,自动配置类就生效,帮我们进行自动配置工作。

public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";public static List loadFactoryNames(Class factoryClass, ClassLoader classLoader) {String factoryClassName = factoryClass.getName();try {// 根据类加载器判断,先从项目资源中查找, 再从系统资源中查找Enumeration urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));List result = new ArrayList();while (urls.hasMoreElements()) {URL url = urls.nextElement();Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));String factoryClassNames = properties.getProperty(factoryClassName);result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));}return result;}catch (IOException ex) {throw new IllegalArgumentException("Unable to load [" + factoryClass.getName() +"] factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex);}
}

J2EE的整体解决方案都和自动配置都在org.springframework.boot.autoconfigure包下面。
在这里插入图片描述

7. Spring Initializer

IDE都支持使用Spring Initializer创建向导快速创建一个SpringBoot项目。

选择我们需要的模块,向导会联网创建SpringBoot项目。
在这里插入图片描述

默认生成的SpringBoot项目:

  • 主程序已经生成好了,我们只需要写我们自己的逻辑。
  • resources文件夹中目录结构
    • static:保存所有的静态资源,js/css/html/images;
    • templates:保存所有的模块页面;(SpringBoot默认jar包使用嵌入式的Tomcat,默认不支持jsp页面, 可以使用模板引擎);
    • application.properties: SpringBoot应用的配置文件。

Eclipse使用spring tool suite插件后也一样的支持快速创建SpringBoot项目。
Spring Tools 4 for Eclipse
在这里插入图片描述

相关内容

热门资讯

如何删除安卓系统信息,安卓系统... 手机里的信息越来越多,是不是感觉自己的隐私都快要被暴露无遗了?别担心,今天就来教你怎么轻松删除安卓系...
国产安卓系统哪个流畅,揭秘哪家... 你有没有想过,手机里的操作系统就像是我们的大脑,有时候它运行得快慢,直接影响我们的使用体验呢?今天,...
安卓怎么刷主机系统,掌握主机系... 你有没有想过,你的安卓手机或者平板,是不是也能像电脑一样,装上各种酷炫的系统呢?没错,今天就要来给你...
安卓系统桌面显示时间,见证日常... 你有没有发现,每次打开安卓手机,那桌面上的时间总是一闪一闪的,仿佛在告诉你:“时间不等人哦!”今天,...
os云刷安卓系统,畅享智能新体... 你有没有想过,你的安卓手机是不是也能像电脑一样,装上各种酷炫的系统呢?没错,今天就要来跟你聊聊这个神...
安卓系统如何装siri,安卓设... 你有没有想过,在安卓手机上也能享受到Siri的智能语音助手服务呢?没错,就是那个在iPhone上呼之...
电脑怎么安卓双系统,电脑安装安... 你有没有想过,一台电脑同时运行安卓和Windows系统,那得多酷啊!想象一边处理工作,一边刷刷抖音,...
linux操作系统与安卓系统,... 你有没有想过,为什么你的手机可以随时随地给你发送信息,而你的电脑却能帮你处理复杂的任务呢?这背后,就...
安卓大屏系统信息,功能与体验全... 你有没有发现,最近手机界的大屏风潮真是势不可挡啊!安卓大屏系统信息,这可是个热门话题呢!想象拿着一块...
苹果7转安卓系统,探索安卓系统... 你有没有想过,从苹果7转到安卓系统会是怎样的体验呢?想象你手中的那个曾经陪伴你度过无数美好时光的苹果...
安卓系统打卡手机推荐,高效便捷... 你有没有想过,每天早上起床后,第一件事就是拿出手机打卡签到?这已经成为现代生活中不可或缺的一部分了。...
安卓手机装了小米系统,小米系统... 你有没有想过,把安卓手机的灵魂换成小米的系统,会是怎样的体验呢?想象原本流畅的安卓系统,突然间被注入...
安卓汽车系统怎么升级,轻松实现... 亲爱的安卓车主们,你是否也像我一样,对汽车系统升级充满了好奇和期待呢?想象你的爱车就像一部智能手机,...
手机怎么变安卓系统,轻松实现系... 你有没有想过,你的手机居然可以变身成为安卓系统呢?没错,就是那个自由度极高的操作系统!今天,就让我来...
安卓仿ios系统横条,打造流畅... 你有没有发现,最近安卓手机上出现了一种特别的新花样——仿iOS系统的横条设计!这可不是简单的模仿,而...
谷歌汽车安卓系统下载,引领智能... 你有没有想过,未来的汽车可能会变成一个移动的智能中心?想象你的汽车不仅能够带你穿梭在城市的大街小巷,...
安卓系统硬件修复软件,全面解析... 手机里的安卓系统突然卡顿,是不是让你头疼不已?别急,今天就来给你揭秘那些神奇的安卓系统硬件修复软件,...
鸿蒙系统比安卓系统大么,体积对... 你有没有想过,手机里的操作系统,就像是手机的心脏,它的大小、性能,都直接影响到手机的使用体验。今天,...
安卓系统 刷机模式,刷机模式操... 你有没有想过,你的安卓手机其实就像一个隐藏着无限可能的宝藏呢?没错,今天就要来跟你聊聊这个宝藏的秘密...
案卷制作系统下载安卓,高效便捷... 你有没有想过,在手机上也能轻松制作案卷呢?没错,现在就有这么一款神器——案卷制作系统,而且它还支持安...