SpringBoot2.5.0快速入门教程

1 Spring Boot入门程序

1.1 Spring Boot是什么?

Spring Boot是一套可以快速创建Spring应用程序的框架,它要实现如下目标:

1、提供更快使用Spring的方案。

2、解决创建Spring应用程序过程使用XML配置的繁琐问题。

大量的XML配置使用整个工程的构建过程非常繁琐,Spring Boot则要解决这个问题。

3、提供一系列大型项目通用的非功能性功能(例如嵌入式服务器,安全性,指标,运行状况检查和外部化配置)。

4、解决复杂的jar包依赖的问题

通常我们需要手动在pom.xml添加大量的依赖,组件不同则添加的依赖也不同,不同的组件还可能会冲突,Spring Boot要解决这个问题。

5、解决组件的配置问题

传统方式是向应用中添加什么组件则配置相应的内容方可正常运行,比如:使用SpringMVC构建一个Web应用则需要配置Http服务的端口号、context-path、视图等信息。但随着添加的组件的越多配置项也越多,Spring Boot要解决这个繁琐。

1.2 Spring Boot环境要求

本次入门程序使用SpringBoot最新发布版本2.5.0,使用2.5.0的要求如下:

至少java8及以上,兼容java16

Spring Framework 要求5.3.7及以上版本

项目构建工具:

Maven :3.5+
Gradle: 6.8.x, 6.9.x, and 7.x

下边在IDEA中配置maven环境:

image-20210528092306483

1.3 代码实现

1.3.1 创建Maven工程

使用idea工具创建一个maven工程,点击File–>New–>Project…

image-20210528092449176

打Maven工程创建界面,该Maven工程就是一个最普通的Java工程。

image-20210528092558340

点击Next,开始填写项目的下标:

image-20210528092712457

点击Next,设置工程名及所在目录。

image-20210528092835942

工程创建成功,下图是工程的目录及初始的pom.xml文件:

image-20210528105306947

1.3.2 添加SpringBoot的起步依赖

所有的SpringBoot项目需要继承SpringBoot的起步依赖spring-boot-starter-parent,本入门程序选用2.5.0版本。

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.pbteach.springboot</groupId>
    <artifactId>springboot_first</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
    </parent>

</project>

1.3.3 添加组件依赖

SpringBoot要集成SpringMVC开发Web应用则需要添加SpringMVC组件,如下:

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

1.3.4 编写Controller

由于添加了SpringMVC组件依赖,即可在项目中使用SpringMVC框架,下边创建Controller类。

下边的Controller类实现请求“/quick”输出"欢迎来到攀博课堂自学Java!",代码如下:

package com.pbteach.stringboot.first.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author 攀博课堂(www.pbteach.com)
 * @version 1.0
 **/

@Controller
public class QuickStartController {

    @RequestMapping("/quick")
    @ResponseBody
    public String quick(){
        return "欢迎来到攀博课堂自学Java!";
    }

}

2.2.5 配置文件

SpringBoot工程默认从classpath下找application.yml配置文件,下边我们配置该文件,文件内容如下:

server:
  port: 8081
  servlet:
    context-path: /springboot_first

application.yml采用YML文件格式,YML文件格式是YAML (YAML Aint Markup Language)编写的文件格式,YAML是一种直观的能够被电脑识别的的数据数据序列化格式,并且容易被人类阅读,比传统的xml方式更加简洁。

YML文件的扩展名可以使用.yml或者.yaml。

1.3.4 编写SpringBoot主方法

Java程序执行的入口就是main方法,下边需要写一个类包含一个main方法。

package com.pbteach.stringboot.first;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author 攀博课堂(www.pbteach.com)
 * @version 1.0
 **/


@SpringBootApplication
public class MySpringBootApplication {

    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApplication.class);
    }

}

该类主要有两部分:

1、@SpringBootApplication注解

2、SpringApplication.run(MySpringBootApplication.class);

稍后解释这两部分的作用。

1.3.5 测试

执行项目的主方法,启动本项目,控制台打印日志如下:

项目默认的端口是8080,如果与本地的8080端口冲突则需要关闭已经启动8080端口的进制。

"D:\Program Files\Java\jdk1.8.0_171\bin\java.exe" -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:55456,suspend=y,server=n -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=55455 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=localhost -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true -javaagent:C:\Users\Administrator\.IntelliJIdea2018.2\system\captureAgent\debugger-agent.jar=file:/C:/Users/Administrator/AppData/Local/Temp/capture.props -Dfile.encoding=UTF-8 -classpath "D:\Program Files\Java\jdk1.8.0_171\jre\lib\charsets.jar;D:\Program Files\Java\jdk1.8.0_171\jre\lib\deploy.jar;D:\Program Files\Java\jdk1.8.0_171\jre\lib\javaws.jar;D:\Program Files\Java\jdk1.8.0_171\jre\lib\jce.jar;D:\Program Files\Java\jdk1.8.0_171\jre\lib\jfr.jar;D:\Program Files\Java\jdk1.8.0_171\jre\lib\jfxswt.jar;D:\Program Files\Java\jdk1.8.0_171\jre\lib\jsse.jar;D:\Program Files\Java\jdk1.8.0_171\jre\lib\management-agent.jar;D:\Program Files\Java\jdk1.8.0_171\jre\lib\plugin.jar;D:\Program Files\Java\jdk1.8.0_171\jre\lib\resources.jar;D:\Program Files\Java\jdk1.8.0_171\jre\lib\rt.jar;D:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\access-bridge-64.jar;D:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\cldrdata.jar;D:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\dnsns.jar;D:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\jaccess.jar;D:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\jfxrt.jar;D:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\localedata.jar;D:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\nashorn.jar;D:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\sunec.jar;D:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\sunjce_provider.jar;D:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\sunmscapi.jar;D:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\sunpkcs11.jar;D:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\zipfs.jar;E:\course\SpringBoot\code\springboot_first\target\classes;F:\develop\maven\repository3\org\springframework\boot\spring-boot-starter-web\2.5.0\spring-boot-starter-web-2.5.0.jar;F:\develop\maven\repository3\org\springframework\boot\spring-boot-starter\2.5.0\spring-boot-starter-2.5.0.jar;F:\develop\maven\repository3\org\springframework\boot\spring-boot-starter-logging\2.5.0\spring-boot-starter-logging-2.5.0.jar;F:\develop\maven\repository3\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;F:\develop\maven\repository3\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;F:\develop\maven\repository3\org\slf4j\slf4j-api\1.7.30\slf4j-api-1.7.30.jar;F:\develop\maven\repository3\org\apache\logging\log4j\log4j-to-slf4j\2.14.1\log4j-to-slf4j-2.14.1.jar;F:\develop\maven\repository3\org\apache\logging\log4j\log4j-api\2.14.1\log4j-api-2.14.1.jar;F:\develop\maven\repository3\org\slf4j\jul-to-slf4j\1.7.30\jul-to-slf4j-1.7.30.jar;F:\develop\maven\repository3\jakarta\annotation\jakarta.annotation-api\1.3.5\jakarta.annotation-api-1.3.5.jar;F:\develop\maven\repository3\org\springframework\spring-core\5.3.7\spring-core-5.3.7.jar;F:\develop\maven\repository3\org\springframework\spring-jcl\5.3.7\spring-jcl-5.3.7.jar;F:\develop\maven\repository3\org\yaml\snakeyaml\1.28\snakeyaml-1.28.jar;F:\develop\maven\repository3\org\springframework\boot\spring-boot-starter-json\2.5.0\spring-boot-starter-json-2.5.0.jar;F:\develop\maven\repository3\com\fasterxml\jackson\core\jackson-databind\2.12.3\jackson-databind-2.12.3.jar;F:\develop\maven\repository3\com\fasterxml\jackson\core\jackson-annotations\2.12.3\jackson-annotations-2.12.3.jar;F:\develop\maven\repository3\com\fasterxml\jackson\core\jackson-core\2.12.3\jackson-core-2.12.3.jar;F:\develop\maven\repository3\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.12.3\jackson-datatype-jdk8-2.12.3.jar;F:\develop\maven\repository3\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.12.3\jackson-datatype-jsr310-2.12.3.jar;F:\develop\maven\repository3\com\fasterxml\jackson\module\jackson-module-parameter-names\2.12.3\jackson-module-parameter-names-2.12.3.jar;F:\develop\maven\repository3\org\springframework\boot\spring-boot-starter-tomcat\2.5.0\spring-boot-starter-tomcat-2.5.0.jar;F:\develop\maven\repository3\org\apache\tomcat\embed\tomcat-embed-core\9.0.46\tomcat-embed-core-9.0.46.jar;F:\develop\maven\repository3\org\apache\tomcat\embed\tomcat-embed-el\9.0.46\tomcat-embed-el-9.0.46.jar;F:\develop\maven\repository3\org\apache\tomcat\embed\tomcat-embed-websocket\9.0.46\tomcat-embed-websocket-9.0.46.jar;F:\develop\maven\repository3\org\springframework\spring-web\5.3.7\spring-web-5.3.7.jar;F:\develop\maven\repository3\org\springframework\spring-beans\5.3.7\spring-beans-5.3.7.jar;F:\develop\maven\repository3\org\springframework\spring-webmvc\5.3.7\spring-webmvc-5.3.7.jar;F:\develop\maven\repository3\org\springframework\spring-aop\5.3.7\spring-aop-5.3.7.jar;F:\develop\maven\repository3\org\springframework\spring-context\5.3.7\spring-context-5.3.7.jar;F:\develop\maven\repository3\org\springframework\spring-expression\5.3.7\spring-expression-5.3.7.jar;F:\develop\maven\repository3\org\springframework\boot\spring-boot-devtools\2.5.0\spring-boot-devtools-2.5.0.jar;F:\develop\maven\repository3\org\springframework\boot\spring-boot\2.5.0\spring-boot-2.5.0.jar;F:\develop\maven\repository3\org\springframework\boot\spring-boot-autoconfigure\2.5.0\spring-boot-autoconfigure-2.5.0.jar;C:\Program Files\JetBrains\IntelliJ IDEA 2018.2.2\lib\idea_rt.jar" com.pbteach.stringboot.first.MySpringBootApplication
Connected to the target VM, address: '127.0.0.1:55456', transport: 'socket'

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.5.0)

2021-05-28 15:55:54.600  INFO 45868 --- [  restartedMain] c.p.s.first.MySpringBootApplication      : Starting MySpringBootApplication using Java 1.8.0_171 on USER-20180531TK with PID 45868 (E:\course\SpringBoot\code\springboot_first\target\classes started by Administrator in E:\course\SpringBoot\code\springboot_first)
2021-05-28 15:55:54.605  INFO 45868 --- [  restartedMain] c.p.s.first.MySpringBootApplication      : No active profile set, falling back to default profiles: default
2021-05-28 15:55:54.694  INFO 45868 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2021-05-28 15:55:54.694  INFO 45868 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2021-05-28 15:55:56.051  INFO 45868 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2021-05-28 15:55:56.064  INFO 45868 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-05-28 15:55:56.065  INFO 45868 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.46]
2021-05-28 15:55:56.169  INFO 45868 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-05-28 15:55:56.170  INFO 45868 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1474 ms
2021-05-28 15:55:56.643  INFO 45868 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2021-05-28 15:55:56.683  INFO 45868 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2021-05-28 15:55:56.695  INFO 45868 --- [  restartedMain] c.p.s.first.MySpringBootApplication      : Started MySpringBootApplication in 2.716 seconds (JVM running for 4.095)
2021-05-28 15:55:56.697  INFO 45868 --- [  restartedMain] o.s.b.a.ApplicationAvailabilityBean      : Application availability state LivenessState changed to CORRECT
2021-05-28 15:55:56.700  INFO 45868 --- [  restartedMain] o.s.b.a.ApplicationAvailabilityBean      : Application availability state ReadinessState changed to ACCEPTING_TRAFFIC

通过日志发现,Tomcat started on port(s): 8080 (http) with context path ‘’

tomcat已经起步,端口监听8080,web应用的虚拟工程名称为空

打开浏览器访问url地址为:http://localhost:8080/quick

image-20210528155633823

1.4 代码解析

1.4.1 启动器

1)spring-boot-starter-parent

Spring Boot 提供很多的启动器,spring-boot-starter-parent就是一个启动器,通过查看它的pom.xml,它继承了spring-boot-dependencies,spring-boot-dependencies里边有很多dependencyManagement,对Spring Boot项目组件的版本进行锁定,另外spring-boot-starter-parent配置了很多插件供项目使用,这就是为什么每个Spring Boot项目需要继承spring-boot-starter-parent的原因。

2) spring-boot-starter-web

spring-boot-starter-web是使用Spring开发web应用的启动器,查看spring-boot-starter-web的pom.xml发现存在SpringMVC框架相关的依赖,部分依赖如下:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-json</artifactId>
  <version>2.5.0</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-tomcat</artifactId>
  <version>2.5.0</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <version>5.3.7</version>
  <scope>compile</scope>
</dependency>

所以,spring-boot-starter-web对SpringMVC框架及相关的jar进行打包,只需要在pom.xml中添加一个spring-boot-starter-web即可使用Spring MVC,大大简化的SpringMVC框架的使用过程。

1.4.2 自动配置

在整个入门程序中没有一个配置项,Spring Boot根据添加的启动器会判断使用了什么组件,从而自动对一些配置项进行配置,比如:端口号默认8080,context-path默认空,当然根据需求也可以对配置项进行个性化配置,这就是Spring Boot的自动配置功能,它和启动器配合加速Spring框架的使用。

1.4.3 springBootApplication

在主方法的类名上有一个@springBootApplication注解,查看它的源代码,如下:

@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 {
    @AliasFor(
        annotation = EnableAutoConfiguration.class
    )
    Class<?>[] exclude() default {};

    @AliasFor(
        annotation = EnableAutoConfiguration.class
    )
    String[] excludeName() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackages"
    )
    String[] scanBasePackages() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackageClasses"
    )
    Class<?>[] scanBasePackageClasses() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "nameGenerator"
    )
    Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class;

    @AliasFor(
        annotation = Configuration.class
    )
    boolean proxyBeanMethods() default true;
}

通过源码发现它组合了@ComponentScan,@EnableAutoConfiguration,@SpringBootConfiguration三个注解。

@ComponentScan:进行bean扫描,可以扫描标记@Service,@Repository,@Component,@Controller的bean。

@SpringBootConfiguration:组合@Configuration注解,声明当前是一个配置类,在类中可以通过@Bean注解声明一个Bean。

@EnableAutoConfiguration:实现自动配置功能。

1.4.4 嵌入式服务器

通过启动日志发现项目在Tomcat下启动运行,Spring Boot项目由于添加了spring-boot-starter-web启动器,这说明本项目是一个web工程,所以嵌入了Tomcat服务器来保证项目的运行。

1.5 创建一个可执行的Jar

1)添加依赖

既然Spring Boot项目可以通过一个main方法启动并运行,完全可以将项目打成一个jar包,通过jar包来运行。

创建可执行jar,首先需要添加spring-boot-maven-pluginpom.xml:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

2)通过IDEA将项目打一个jar包,如下:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JV52rv56-1622298368172)(http://img.pbteach.com/pbresource/image/course/springboot/image-20210528170909938.png)]

3)整个过程也可以使用maven命令:mvn package

首先保证本地maven环境配置正确。(maven的相关内容不再赘述,不熟悉的可以参考攀博课堂提供的maven课程下载视频)

切换到Terminal,输入mvn package命令,打包成功:

image-20210528171222494

4)找到jar包,运行

jar包在工程的target目录,找到它,使用java -jar运行

image-20210528171343473

按住shift键盘,右键点击:在此处打开命令窗口

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-A0UZ7Kqz-1622298368175)(http://img.pbteach.com/pbresource/image/course/springboot/image-20210528171441878.png)]

在cmd窗口中输入 java -jar springboot_first-1.0-SNAPSHOT.jar

image-20210528171635097

通过日志发现启动成功,浏览器访问http://localhost:8080/quick 一切正常。

2 SpringBoot的配置文件

2.1 配置文件分类

虽然Spring Boot有自动配置,但也需要对某些参数进行手动配置,比如:更改应用的端口号,设置context-path等。

SpringBoot主要有两类配置文件格式:properties和yml/yaml,前者是键值对格式,后者是YML格式。

键值对格式的例子如下:

server.port=8080 # Server HTTP port.
server.servlet.context-path= /# Context path of the application.

YML格式的例子如下:

server:
  port: 8080 #设置端口号
  servlet:
    context-path: /

可以看出YML格式的好处比键值对的配置方式更加有层次、更容易阅读。YML文件格式是YAML (YAML Aint Markup Language)编写的文件格式,YML文件的扩展名可以使用.yml或者.yaml。

2.2 默认配置文件

2.2.1 application.yml

Spring Boot默认的配置文件名称为application,application.properties、application.yml、application.yaml是Spring Boot的默认配置文件,application.properties是键值对配置文件,application.yml和application.yaml是YML格式配置文件。

Spring Boot默认会加载resources目录下的配置文件,当默认配置文件都存在时它们的优先级为:properties > yml > yaml,不过一般不会同时存在,会选一种格式的配置文件。本文主要介绍YML格式的配置文件。

下边在resources目录下配置application.yml如下:

server:
  port: 8080 #设置端口号
  servlet:
    context-path: /

这里配置了http服务的端口号及servlet的context-path,可以看出它们是有一定的层次,初次接触YML的人可能不习惯,觉得没有properties好,当配置项多了就能体现YML的好处了,如上边的配置,port、servlet都隶属于server下,context-path隶属于servelt,这样看起来更清晰。

可以尝试修改application.yml文件的内容,重启项目并测试,比如:修改port为8081,修改保存后重启项目测试

http://localhost:8081/quick是否可以访问,可以访问说明配置文件生效。

2.2.2 配置信息的查询

Spring Boot集成了很多常用的组件,每个组件在Spring Boot中都有相应的配置信息,可以通过如下链接查询全部的配置信息清单:

https://docs.spring.io/spring-boot/docs/2.5.0/reference/htmlsingle/#application-properties

内容目录如下:

image-20210529071510008

以Server Properties为例,打开它:

image-20210529071948979

2.3 YML语法

2.3.1 基本语法

YML的基本语法如下:

1、大小写敏感

2、数据值前边必须有空格(空格多少不限定),作为分隔符

3、使用缩进表示层级关系

4、缩进的空格数目不重要,只要相同层级的元素左侧对齐即可,建议用Tab键缩进。

6、# 表示注释,从这个字符一直到行尾,都会被解析器忽略,#前要至少有一个空格。

2.3.2 数据格式

1、单个map数据

语法:

key: value

示例代码:

name: 攀博课堂
url: www.pbteach.com

2、对象map数据

语法:

key: 
	key1: value1
	key2: value2
或者:
key: {key1: value1,key2: value2}

示例代码:

server:
  port: 8080 #设置端口号
  address: 127.0.0.1 #服务地址

注意:相同的缩进代表一个层级。

address和port都隶属于server,且它们是一个层次,下边的配置address的缩进和port不同,表示address隶属于port,是错误的。

server:
  port: 8080 #设置端口号
    address: 127.0.0.1 #服务地址

3、数组格式

语法:

key: 
 - value1
 - value2
 - value3

短横 “-” 标记着一个元素的开始,每个短横前是相同的缩进,每个短横后有一个空格。

示例代码:

urls:
  - www.pbteach.com
  - pbteach.com
  - img.pbteach.com

也可以配置为对象map的数组,如下:

servers:
  - name: 攀博课堂主站
    url: www.pbteach.com
  - name: 攀博课堂图片服务
    url: img.pbteach.com

或者:

servers[0]:
	name: 攀博课堂主站
	url: www.pbteach.com
servers[1]:
	name: 攀博课堂图片服务
	url: img.pbteach.com

4、引用数据格式

语法:

${key}

示例如下:

server:
  port: 8080 #设置端口号
  address: 127.0.0.1 #服务地址
servers:
  - name: 攀博课堂主站
    url: www.pbteach.com
    port: ${server.port}
  - name: 攀博课堂图片服务
    url: img.pbteach.com
    port: ${server.port}

${server.port}表示引用了server下port的值。

2.3.3 读取配置文件内容

2.3.3.1ConfigurationProperties注解

前边了解了不同的数据格式,下边介绍配置文件的读取方式,即将配置文件中的数据读取到类的属性中。

1、首先在application.yml中配置如下内容:

pbteach:
  name: 攀博课堂
  url: www.pbteach.com
  urls:
    - www.pbteach.com
    - pbteach.com
    - img.pbteach.com
  servers:
    - name: 攀博课堂主站
      url: www.pbteach.com
    - name: 攀博课堂图片服务
      url: img.pbteach.com

2、@ConfigurationProperties

@ConfigurationProperties是Spring Boot下的注解,它标记在类上,可将配置文件中的信息映射到类的属性上。

依据上边的配置文件内容,下边创建PbConfig类用于存储配置信息,如下:

package com.pbteach.stringboot.first.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * @author 攀博课堂(www.pbteach.com)
 * @version 1.0
 **/
//prefix表示取出以某个前缀的开头的配置信息,如果要从根元素开始取则prefix配置为""空字符串即可
@ConfigurationProperties(prefix = "pbteach")
//一定要用@Configuration,表示它是一个配置bean
@Configuration
public class PbConfig {
    String name;
    String url;
    String[] urls;
    Server[] servers;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String[] getUrls() {
        return urls;
    }

    public void setUrls(String[] urls) {
        this.urls = urls;
    }

    public Server[] getServers() {
        return servers;
    }

    public void setServers(Server[] servers) {
        this.servers = servers;
    }

    public static class Server{
        String name;
        String url;

        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getUrl() {
            return url;
        }
        public void setUrl(String url) {
            this.url = url;
        }
    }
}

3、在conroller类中读取PbConfig对象的信息

首先将PbConfig注入到Controller类,在方法中可输出PbConfig对象中的属性,代码如下:

package com.pbteach.stringboot.first.controller;

import com.pbteach.stringboot.first.config.PbConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author 攀博课堂(www.pbteach.com)
 * @version 1.0
 **/

@Controller
public class QuickStartController {

    @Autowired
    PbConfig pbConfig;

    @RequestMapping("/quick")
    @ResponseBody
    public String quick(){
        System.out.println(pbConfig.getName());
        System.out.println(pbConfig.getUrl());
        String[] urls = pbConfig.getUrls();
        System.out.println(urls[0]);
        return "欢迎来到 攀博课堂自学Java!";
    }


}

访问http://localhost:8081/quick,观察控制台:

攀博课堂
www.pbteach.com
www.pbteach.com
2.3.3.2 Value注解

1、@Value注解

@Value注解是Spring中的注解,它标记在类的属性上且支持SpEL表达式,@Value不能获取以短横开头的数组元素,通常用@Value注解获取单个key的值。也有一些方法可以获取数组,不过使用不多,这里不作介绍。

2、下边演示用@Value注解获取key对应的值

1)首先属性上用@Value指定key

@Value("${pbteach.name}")
String name;
@Value("${pbteach.url}")

2)在方法中即可读取name、url的值

   System.out.println(name);
    System.out.println(url);

3)完整代码如下

package com.pbteach.stringboot.first.controller;

import com.pbteach.stringboot.first.config.PbConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author 攀博课堂(www.pbteach.com)
 * @version 1.0
 **/

@Controller
public class QuickStartController {

    @Value("${pbteach.name}")
    String name;
    @Value("${pbteach.url}")
    String url;
    @Autowired
    PbConfig pbConfig;

    @RequestMapping("/quick")
    @ResponseBody
    public String quick(){
        System.out.println(name);
        System.out.println(url);
        System.out.println(pbConfig.getName());
        System.out.println(pbConfig.getUrl());
        String[] urls = pbConfig.getUrls();
        System.out.println(urls[0]);
        return "欢迎来到 攀博课堂自学Java!";
    }


}

2.4 Profile

2.4.1 Profile介绍

一个项目的配置信息通常在开发环境、测试环境、生产环境是不同的,比如:在开发阶段连接的数据库和正式的生产环境下是不同的,可以试想,如果准备将项目部署到生产环境时将数据库的地址改为生产环境的数据库地址,或者还有其它的配置需要修改,这是非常麻烦的。Spring Boot Profile可以解决这个问题,它可以非常方便的切换每个环境的配置。

2.4.2 Profile配置方式

Profile是如何动态的切换环境呢?

首先需要将不同环境的配置信息有规则的分开配置,将每个环境的配置文件名称按 application-{profileName}.yml 的方式定义

比如:开发环境、测试环境、生产环境的配置文件命名如下:

开发环境:application-dev.properties/yml

测试环境:application-test.properties/yml

生产环境:application-pro.properties/yml

再加一个主配置文件application.yml,项目的配置文件清单如下:

1)主配置文件:application.yml

配置通用的不用根据环境不同区别配置的信息。

2)开发环境:application-dev.properties/yml

配置开发环境下的个性配置信息。

3)测试环境:application-test.properties/yml

配置测试环境下的个性配置信息。

4)生产环境:application-pro.properties/yml

配置生产环境下的个性配置信息。

下边配置开发和生产两个环境的配置进行测试:

主配置文件内容如下:

mybatis:
  type-aliases-package: com.pbteach.stringboot.first.entity
  mapper-locations: classpath:dao/*Mapper.xml
pbteach:
  name: 攀博课堂
  url: www.pbteach.com
  urls:
    - www.pbteach.com
    - pbteach.com
    - img.pbteach.com
  servers:
    - name: 攀博课堂主站
      url: www.pbteach.com
    - name: 攀博课堂图片服务
      url: img.pbteach.com
#
#  servers[0]:
#    name: 攀博课堂主站
#    url: www.pbteach.com
#  servers[1]:
#    name: 攀博课堂图片服务
#    url: img.pbteach.com
#spring:
#  devtools:
#    restart:
#      enabled: true #使用热部署生效
#      exclude: WEB-INF/**  #WEB-INF下的文件内容修改后不热部署
#      additional-paths: src/main/java #该目录下的类文件修改后开始热部署

开发环境的配置如下:

server:
  port: 8081 #设置端口号
  servlet:
    context-path: /springboot_first
spring:
  datasource:
    driverClassName: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/springboot_first?useUnicode=true&characterEncoding=utf8
    username: root
    password: mysql

生产环境的数据库密码和context-path与开发环境不同,配置如下:

server:
  port: 8081 #设置端口号
  servlet:
    context-path: /
spring:
  datasource:
    driverClassName: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/springboot_first?useUnicode=true&characterEncoding=utf8
    username: root
    password: pbteach

2.4.3 激活配置

将配置信息配置完成后,需要根据环境的不同去激活某个配置文件,比如:在开发环境下需要激活开发环境的配置,在生产环境下需要激活生产环境的配置。

如何激活某个环境的配置?

激活配置的方式有:配置文件、虚拟机参数两种方式。

1、首先介绍通常配置文件激活方式:

在主配置文件中使用spring.profiles.active激活某个配置。

测试一:

在主配置文件中激活开发环境配置,如下:

spring:
  profiles:
    active: dev

启动项目,访问http://localhost:8081/springboot_first/quick 访问正常说明激活配置生效。

image-20210529162153701

测试二:

在主配置文件中激活生产环境配置,如下:

spring:
  profiles:
    active: pro

重新启动项目,访问http://localhost:8081/quick 访问正常说明激活配置生效。

2、通过虚拟机参数激活

在VM options 指定:-Dspring.profiles.active=名称

通过Edit Configurations…进入设置

image-20210529163750555

image-20210529163813880

推荐虚拟机参数方式激活,在启动项目时传入参数,如下:

java -Dspring.profiles.active=pro -jar springboot_first-1.0-SNAPSHOT.jar

3 SpringBoot与整合第三方组件

3.1 SpringBoot整合Mybatis

3.1.1 添加Mybatis的起步依赖

<!--mybatis起步依赖-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>

3.1.2 添加数据库驱动坐标

<!-- MySQL连接驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

3.1.3 添加数据库连接信息

在application.properties中添加数据量的连接信息

#DB Configuration:
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot_first?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root

3.1.4 创建user表

在test数据库中创建user表

-- ----------------------------
-- Table structure for `pb_user`
-- ----------------------------
DROP TABLE IF EXISTS `pb_user`;
CREATE TABLE `pb_user` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `username` VARCHAR(50) DEFAULT NULL,
  `password` VARCHAR(50) DEFAULT NULL,
  `name` VARCHAR(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of pb_user
-- ----------------------------
INSERT INTO `pb_user` VALUES ('1', 'pbteach', '123', '传智燕青');

3.1.5 创建实体Bean

package com.pbteach.stringboot.first.entity;

/**
 * @author 攀博课堂(www.pbteach.com)
 * @version 1.0
 **/
public class PbUser {
    // 主键
    private Long id;
    // 用户名
    private String username;
    // 密码
    private String password;
    // 姓名
    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

3.1.6 编写Mapper

package com.pbteach.stringboot.first.dao;

import com.pbteach.stringboot.first.entity.PbUser;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * @author 攀博课堂(www.pbteach.com)
 * @version 1.0
 **/
@Mapper
public interface PbUserMapper {
    public List<PbUser> queryUserList();
}

注意:@Mapper标记该类是一个mybatis的mapper接口,可以被spring boot自动扫描到spring上下文中

3.1.7 配置Mapper映射文件

在src\main\resources\dao路径下加入PbUserMapper.xml配置文件"

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.pbteach.stringboot.first.dao.PbUserMapper">
    <select id="queryUserList" resultType="pbUser">
        select * from pb_user
    </select>
</mapper>

3.1.8 在application.properties中添加mybatis的信息

#spring集成Mybatis环境
mybatis:
  type-aliases-package: com.pbteach.stringboot.first.entity
  mapper-locations: classpath:dao/*Mapper.xml

3.1.9 编写测试Controller

@Controller
public class QuickStartController {

    
    @Autowired
    private PbUserMapper pbUserMapper;

    @RequestMapping("/queryUser")
    @ResponseBody
    public List<PbUser> queryUser(){
        List<PbUser> users = pbUserMapper.queryUserList();
        return users;
    }

}

3.1.10 测试

在浏览器请求:http://localhost:8081//queryUser

image-20210529115820033

3.2 SpringBoot整合Junit

3.2.1 添加Junit的起步依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

3.2.2 编写测试类

package com.pbteach.springboot.first;

/**
 * @author 攀博课堂(www.pbteach.com)
 * @version 1.0
 **/

import com.pbteach.stringboot.first.MySpringBootApplication;
import com.pbteach.stringboot.first.dao.PbUserMapper;
import com.pbteach.stringboot.first.entity.PbUser;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest(classes = MySpringBootApplication.class)
public class MapperTest {

    @Autowired
    private PbUserMapper pbUserMapper;

    @Test
    public void test() {
        List<PbUser> users = pbUserMapper.queryUserList();
        System.out.println(users);
    }

}

执行测试,控制台输出:

[PbUser{id=1, username='pbteach', password='123', name='传智燕青'}]

到此说明Junit和Spring Boot整合成功。
原文:http://www.pbteach.com/java/java_05_01/index.html

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值