【SpringBoot 2学习笔记】《一》入门初体验

一、SpringBoot2入门介绍

1.1、SpringBoot特性介绍

Spring Boot整体上简化开发Spring应用的框架构成,整合了Spring关联技术栈,提供了J2EE开发的一站式解决方案。其主要特点如下:

  • Spring Boot伴随着Spring 4.0诞生的,继承了Spring框架原有的优秀基因。

  • 遵循“约定优先于配置”的原则,使用Spring Boot只需很少的配置,大部分的时候直接使用默认的配置即可。SpringBoot会根据项目依赖来自动配置Spring框架,极大减少了项目所使用的配置。

  • 对主流开发框架无配置集成,自动整合第三方框架。

  • Spring Boot可以JAR包的形式独立运行。使用java -jar命令或者在项目的主程序中执行main函数就可以成功运行项目。

  • Spring Boot内嵌Servlet 容器,可以选择内嵌Tomcat、Jetty 等Web容器,无须以war包形式部署项目。

  • 提供starter简化Maven配置,基本上可以做到自动化配置,高度封装,开箱即用。

  • Spring Boot提供了准生产环境的应用监控。

  • 支持分布式开发,与Spring Cloud的微服务无缝结合。

1.2、RESTful风格微服务

RESTful架构风格规定,数据的元操作,即CRUD(增删查改)操作,分别对应于HTTP方法:GET用来获取资源,POST用来新建资源(也可以用于更新资源),PUT用来更新资源,DELETE用来删除资源,这样就统一了数据操作的接口,仅通过HTTP方法,就可以完成对数据的所有增删查改工作。

  • GET(SELECT):从服务器取出资源(一项或多项)。

  • POST(CREATE):在服务器新建一个资源。

  • PUT(UPDATE):在服务器更新资源(客户端提供完整资源数据)。

  • PATCH(UPDATE):在服务器更新资源(客户端提供需要修改的资源数据)。

  • DELETE(DELETE):从服务器删除资源。

1.3、环境准备

项目中使用环境及相关要求如下:

  • JDK:Spring Boot 2.0 要求 Java 8 作为最低版本,现在许多现有的API已更新,以便利用 Java 8 的特性,例如:接口上的默认方法,函数回调以及新的 API。

  • Maven:Maven 3.3以上

  • IDE:SpringToolSuite4( https://spring.io/tools

  • SpringBoot 2.X

1.4、SpringBoot2入门之HelloWorld

因为Spring官方提供的STS已经整合了开发的相关各种组件,所以下载下来后可以直接使用。如果你使用标准的Eclipse的话,需要进行Maven,STS插件的安装,可以自行百度解决。接下来使用STS4来进行第一个SpringBoot微服务的开发,采用经典的HelloWorld作为示例。

1、点击熟悉的菜单File→New→Spring Starter Project创建项目,如下图所示。也可以选择Project在选用具体的我们需要创建的项目。

2、使用 https://start.spring.io/ 快速创建一个SpringBoot2项目

※ 注意: 因为是入门的HelloWorld,因此没有引入太多的内容。在现实的开发中,可能还需要选择NoSQL 开发工具(例如Redis、MongoDB等),还有数据库MySQL,以及持久层MyBatis等项目的依赖。

3、默认创建的工程因为引用Junit版本导致默认生成的代码有红色错误。我们通过在POM文件中引入对应的 JUnit5来解决该问题。

    <!-- Junit 5 -->
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-params</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-engine</artifactId>
      <scope>test</scope>
    </dependency>

4、现在我们创建一个HelloController来演示运行的过程。浏览器发送hello请求,服务器接受请求并处理,响应欢迎的字符串。

HelloController.java

package com.example.demo.controller;
​
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
​
@RestController
@RequestMapping("/api")
public class HelloController {
​
    @GetMapping("/hello/{userName}")
    public String hello(@PathVariable("userName") String userName) {
        return "Welcome To SpringBoot 2 : " + userName;
    }
}

5、启动我们的SpringBoot项目并验证。

使用右键选择启动类,可以通过途中标记的两中方式启动。两种方式的区别是使用“Run As Spring Boot APP”时,main函数中STS会为我们添加启动参数。具体可以自行打断点查看。

启动后使用浏览器访问我们的第一个应用接口地址。返回结果如下:

1.5、SpringBoot2 HelloWorld分析

1.5.1 POM文件说明

POM文件主要是描述SpringBoot2.x中Maven的配置内容,所以称之为项目对象模型(Project Object Model),其主要内容参考如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  
  <!-- 依赖的SpringBoot父类,包含了大量配置好的依赖管理方便版本统一管理,后面项目添加依赖时,依赖的版本和父类一致的可以不用写新添加依赖的版本号 --> 
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.0.BUILD-SNAPSHOT</version> <!-- 具体的Spring Boot版本 -->
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  
  <!-- 项目工程信息:Maven GAV坐标 -->
  <!-- 组织机构/顶层项目 -->
  <groupId>com.example</groupId>
  <!-- 项目/库 -->
  <artifactId>HelloWorld</artifactId>
  <!-- 唯一发行版本号 -->
  <version>0.0.1-SNAPSHOT</version>
  <!-- 项目名称 -->
  <name>HelloWorld</name>
  <!-- 项目描述 -->
  <description>Demo project for Spring Boot</description>
  <!--Maven打包项目的方式:jar或者war -->
  <packaging>jar</packaging>
​
  <!-- 配置项信息,例如JDK版本(必配),编码类型等其他配置信息 -->
  <properties>
    <java.version>1.8</java.version>
  </properties>
​
  <dependencies>
    <!-- 创建SpringBoot的WEB项目时,WEB启动器(默认集成tomcat)  -->
    <!-- 注意spring-boot-starter-web 而不是 spring-boot-starter -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
​
    <!--测试启动器 可以不用考虑-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <groupId>org.junit.vintage</groupId>
          <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    
    <!-- SpringBoot2.X 需要引入Junit5 解决默认4.X中注解问题 -->
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-params</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-engine</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
​
  <!-- 引用插件:直接使用Maven来进行编译打包 -->
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
​
  <repositories>
    <!-- 用来配置maven项目的远程仓库, 现在使用默认。也可以搭建自己的Maven库 -->
    <repository>
      <id>spring-milestones</id>
      <name>Spring Milestones</name>
      <url>https://repo.spring.io/milestone</url>
    </repository>
    <repository>
      <id>spring-snapshots</id>
      <name>Spring Snapshots</name>
      <url>https://repo.spring.io/snapshot</url>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </repository>
  </repositories>
  
  <pluginRepositories>
    <!-- 用来配置maven插件的远程仓库 -->
    <pluginRepository>
      <id>spring-milestones</id>
      <name>Spring Milestones</name>
      <url>https://repo.spring.io/milestone</url>
    </pluginRepository>
    <pluginRepository>
      <id>spring-snapshots</id>
      <name>Spring Snapshots</name>
      <url>https://repo.spring.io/snapshot</url>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </pluginRepository>
  </pluginRepositories>
​
</project>

注意:pom.xml 文件修改保存后,Maven自动下载所需的JAR

1.5.2 SpringBoot入口类

package com.example.demo;
​
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
​
/**
 *  @SpringBootApplication 标注这是SpringBoot项目的主程序类
 */
@SpringBootApplication
public class HelloWorldApplication {
​
  public static void main(String[] args) {
    
    // SpringApplication: 从main方法启动Spring应用的类
    SpringApplication.run(HelloWorldApplication.class, args);
  }
​
}

​@SpringBootApplication: Spring Boot应用,该应用标注在某个类上就说明这个类是SpringBoot的主配置类,SpringBoot就运行这个类的main方法来启动SpringBoot应用。

我们来看一下SpringBootApplication:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
// Spring Boot的配置类
@SpringBootConfiguration
// 开启自动配置功能。这个注解告诉SpringBoot开启自动配置功能,只有加上该注解后,自动配置才能生效;
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
    @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
@ConfigurationPropertiesScan
public @interface SpringBootApplication {

1.5.3 启动控制台

根据控制台的信息可以了解当前工程的Spring Boot的版本、Apache Tomcat 的版本、监听的端口、Spring WebApplicationContext创建信息等日志信息。另外,在信息上方看到了一个Spring 的图形,该图形还可以自行定制。 ​

​
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v2.2.0.BUILD-SNAPSHOT)
​
// 启动应用
2019-11-10 10:48:35.448  INFO 14048 --- [           main] com.example.demo.HelloWorldApplication   : Starting HelloWorldApplication on 20190823-032019 with PID 14048 (C:\StsEclipse4.3.2\workspace\HelloWorld\target\classes started by Administrator in C:\StsEclipse4.3.2\workspace\HelloWorld)
// 查找active profile,没有设定的情况下则设为default。
2019-11-10 10:48:35.452  INFO 14048 --- [           main] com.example.demo.HelloWorldApplication   : No active profile set, falling back to default profiles: default
// 进行Tomcat初始化,端口默认设定为8080,设置访问方式为http。
2019-11-10 10:48:36.973  INFO 14048 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
// 启动Tomcat服务。
2019-11-10 10:48:36.989  INFO 14048 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
// 启动Servlet引擎。
2019-11-10 10:48:36.989  INFO 14048 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.27]
// 初始化Spring内嵌的WebApplicationContext。
2019-11-10 10:48:37.096  INFO 14048 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
// 完成Spring内嵌的WebApplicationContext的初始化。
2019-11-10 10:48:37.097  INFO 14048 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1560 ms
2019-11-10 10:48:37.278  INFO 14048 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
// Tomcat启动完成
2019-11-10 10:48:37.450  INFO 14048 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
// 整个应用启动时间
2019-11-10 10:48:37.453  INFO 14048 --- [           main] com.example.demo.HelloWorldApplication   : Started HelloWorldApplication in 2.415 seconds (JVM running for 3.015)

1.5.4 配置文件

SpringBoot2使用一个全局的配置文件,文件名是固定的,可以在Spring Boot项目的src/main/resources目录下或者在类路径的/config目录下创建一个全局的配置文件application.properties或者是后缀为.yml的application.yml文件。通过修改配置文件的配置项来修改SpringBoot自动配置的默认值,SpringBoot2在底层都给我们自动配置好。在实际开发中我比较习惯使用application.properties文件作为应用的全局配置文件。

  • application.properties

  • application.yml

※YML文件格式是YAML (YAML Aint Markup Language)编写的文件格式,YAML是一种直观的能够被电脑识别的的数据数据序列化格式,并且容易被人类阅读,容易和脚本语言交互的,可以被支持YAML库的不同的编程语言程序导入。YML文件是以数据为核心的,比传统的xml方式更加简洁。

发布了24 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/gavinbj/article/details/102995665