SpringBoot笔记

# 一、SpringBoot入门

## 1.SpringBoot概述

SpringBoot简化Spring开发的

提供约定大于配置的原则

特点:

* 创建独立的Spring应用程序

* 嵌入的Tomcat,无需部署WAR文件

* 简化Maven配置

* 自动配置Spring

* 提供生产就绪型功能,如指标,健康检查和外部配置

* 绝对没有代码生成并且对XML也没有配置要求

## 2.微服务

微服务只是一种架构风格

一组微小的服务,并且运行在各自的**进程**中,服务之间基于HTTP进行通信

http://blog.cuicc.com/blog/2015/07/22/microservices/(建议阅读)

![](assets/sketch.png)

每个模块都是可以独立升级独立部署的功能单元

SpringBoot就可以用来开发这些独立的功能单元

## 3.SpringBoot快速入门

需求:编写一个处理器,对/helloworld请求进行处理,并在页面返回helloworld字符串

> 3.1环境配置

- A favorite text editor or IDE
- [JDK 1.8](http://www.oracle.com/technetwork/java/javase/downloads/index.html) or later
- [Gradle 4+](http://www.gradle.org/downloads) or [Maven 3.2+](https://maven.apache.org/download.cgi)
- You can also import the code straight into your IDE:
  - [Spring Tool Suite (STS)](https://spring.io/guides/gs/sts)
  - [IntelliJ IDEA](https://spring.io/guides/gs/intellij-idea/)

> 3.2创建项目

创建java工程,打包方式jar包

> 3.3添加依赖(pom.xml)

```xml
<!-- 添加父工程依赖 -->
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
    </parent>

<!--添加依赖-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
```

> 3.4 编写Controller

```java
/*@Controller
@ResponseBody*/
@RestController
public class HelloWorldController {

    @RequestMapping("/helloworld")
    public String sayHello(){
        return "hello world";
    }
}
```

> 3.5 编写主程序类

```java
/**
 * 主程序类
 *
 * @SpringBootApplication 声明当前类是SpringBoot主程序类
 * SpringBoot应用启动时,会默认执行被@SpringBootApplication注解所修饰的类的main方法
 */
@SpringBootApplication
public class HelloWorldApplication {
    public static void main(String[] args) {
        //运行Spring应用程序
        SpringApplication.run(HelloWorldApplication.class,args);
    }
}
```

> 3.6 启动

如果出现端口被占用(默认使用8080端口)

1. 释放8080端口
2. 修改springboot应用的默认端口(springboot默认配置文件 application.properties/application.yml 文件名不能修改,因为springboot应用启动时默认就会加载配置文件)

```properties
# 修改默认8080端口
server.port=8086
```

> 3.7 打包

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

## 4.SpringBoot原理分析

### 4.1 主程序类

**@SpringBootApplication** 声明当前类是一个主程序类

SpringBoot启动时会执行该注解修饰的类的main方法
**位置很重要!!**

@SpringBootApplication

> @SpringBootConfiguration

SpringBoot配置类 作用等同于Spring配置类@Configuration=>类似于配置文件(applicationContext.xml)

```xml
applictionContext.xml

<beans>
    <bean id="" class=""></bean>
    <bean id="" class=""></bean>
</beans>
```

声明该类是一个配置类

> @EnableAutoConfiguration 开启自动配置

> > @AutoConfigurationPackage 自动配置打包

> > >  @Import({Registrar.class}) @Import:向容器中添加组件

springboot应用启动时,默认加载主程序类所对应的包以及子包下的所有组件

类似于 <component:scan>

> > @Import({AutoConfigurationImportSelector.class})

向容器中导入组件,导入哪些组件,由下面方法决定

```java
 public String[] selectImports(AnnotationMetadata annotationMetadata) {
        if (!this.isEnabled(annotationMetadata)) {
            return NO_IMPORTS;
        } else {
            AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);
            AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
            List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
            configurations = this.removeDuplicates(configurations);
            Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
            this.checkExcludedClasses(configurations, exclusions);
            configurations.removeAll(exclusions);
            configurations = this.filter(configurations, autoConfigurationMetadata);
            this.fireAutoConfigurationImportEvents(configurations, exclusions);
            return StringUtils.toStringArray(configurations);
        }
    }
```

![](assets/configurations.JPG)

springboot应用启动的时候会读取META-INF/spring.factories加载很多自动配置类进行自动配置(xxxAutoConfiguration),所以很多组件都不需要我们自己手动配置,springboot都默认加载好了

### 4.2 pom.xml

> 添加父工程依赖

```xml
<!--添加父工程依赖-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
    </parent>
```

父工程的父工程

```xml
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>2.0.5.RELEASE</version>
        <relativePath>../../spring-boot-dependencies</relativePath>
    </parent>
```

版本仲裁中心,锁定了很多常用的依赖的版本,所以我们在工程中添加依赖的时候,可以不写版本号

但是,如果没有被父工程锁定的依赖,还是需要些写版本号

> spring-boot-starter-web

```xml
<!--添加依赖-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
```

spring-boot-starter springboot启动器

-web

spring-boot-starter-web:统一添加了web开发场景中所需要的所有的依赖

SpringBoot将我们日常开发的场景进行了统一的抽取,抽取成一个个启动器,当我们要使用什么场景的时候直接添加该场景启动器即可。

## 5.Spring Initializr快速创建SpringBoot应用

保证**联网**

![](assets/init.JPG)

选择我们需要的模块

基本springboot模板创建完成,我们只需要添加业务即可

默认创建的资源文件:

static: 静态资源文件 比如:js、css

templates: 存放页面模板 thymeleaf、freemarker(jsp springboot内置的tomcat不支持jsp)

application.properties: springboot的默认配置文件(格式固定)

## 6.SpringBoot配置文件

springboot应用启动的时候,会默认加载application.properties、application.yml配置文件(文件名固定的)

application.properties

application.yml

作用:修改springboot的默认配置属性

### 6.1 YAML

YAML Ain't Markup Language

常见配置文件格式:properties xml ...

以数据为中心,更适合做配置文件  键值对

格式:

键:[空格]值  **注意:空格一定不能省略**

使用空格来控制数据的层级关系,只要是左对齐都是属于同一级别

#### 6.1.1 YAML值

> 字面量(字符串、数值、布尔...)

默认情况下,字面量不需要使用单引号以及双引号,直接写值

双引号: 不会转义字符串中的特殊字符,特殊字符会作为它想表达的意思

“hello \n world”  => "hello 换行 world"

单引号:转义字符串中的特殊字符,特殊字符会作为字符串输出

“hello \n world” => “hello \n world” 

> 对象、map

```pro
  dog:
    name: 旺财
    age: 2
```

行内写法:

```
dog2: {name: 来福,age: 3}
```

> 数组、集合

```
hobby:
  - java
  - c#
  - ios
```

行内写法:

```
hobby: [java,c#,ios]
```

##  6.2 批量注入属性的值

```java
/**
 * ConfigurationProperties 将该注解修饰的类的属性与配置文件进行关联
 * 使用该注解的前提:该类必须是容器中组件
 * prefix:指定配置的前缀
 *
 * */
@Component
@ConfigurationProperties(prefix = "person")
public class Person {

    private String name;
    private int age;
    private boolean girl;
    private Dog dog;
    private Dog dog2;
    private List<String> hobby;
}
```

|                | @ConfigurationProperties | @Value       |
| :------------- | ------------------------ | ------------ |
| 功能           | 批量加载属性             | 设置单个属性 |
| 松散绑定       | 支持                     | 不支持       |
| spEL           | 不支持                   | 支持         |
| 复杂对象       | 支持                     | 不支持       |
| JSR303数据校验 | 支持                     | 不支持       |

具体使用哪个根据使用情况决定

## 6.3 使用@PropertySource加载指定配置文件

```java
/**
 * ConfigurationProperties 将该注解修饰的类的属性与配置文件进行关联
 * 使用该注解的前提:该类必须是容器中组件
 * prefix:指定配置的前缀
 *
 * @PropertySource:加载指定配置文件
 * 注意:在使用该注解的时候不能使用YAML配置文件
 * */

@PropertySource(value = "classpath:person.properties")
@Component
@ConfigurationProperties(prefix = "person")
//@Validated
public class Person {
```

```pro
person.age=20
person.girl=true
person.dog.name=旺财
person.dog.age=2
person.dog2.name=来福
person.dog2.age=3
person.hobby=[java,c#,ios]
person.name=12233@qq.com
person.username="jack"
```

## 6.4 加载spring配置文件

springboot中不推荐编写spring配置文件,建议使用配置类(@Configuration+@Bean)

如果需要编写spring配置文件,则需要在主程序类上声明加载文件

```java
@SpringBootApplication
//加载spring配置文件(默认不会加载)
@ImportResource(locations = {"classpath:applicationContext.xml"})
public class SpringbootInitApplication {

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

}
```

## 6.5 随机数配置

```xml
my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.uuid=${random.uuid}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}
```

引用之前定义过的变量

```pro
person.age=${random.int}
# person.name=张三
person.girl=true
# 获取已定义的变量 如果获取不到则采用默认值
person.dog.name=${person.name:未知}的狗
```

## 7.多Profile配置

### 7.1 properties 多环境配置

默认配置文件:application.properties

多环境配置文件:application-{profile}.properties

eg: application-dev.properties、application-prod.properties

在默认配置文件中,可以切换当前的环境配置:

* 通过配置文件激活

```properties
# 激活指定环境
spring.profiles.active=prod
```

* 通过启动参数激活

java -jar springboot_init-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod

* 通过JVM参数设置

-Dspring.profiles.active=prod

```
java -jar -Dspring.profiles.active=production demo-0.0.1-SNAPSHOT.jar
```

### 7.2 YAML多环境配置

通过**---**分割多个文档

```prop
server:
  port: 8085
  servlet:
    context-path: /aaa
spring:
  profiles:
    active: dev
---
server:
  port: 8086
  servlet:
    context-path: /bbb
# 定义当前的环境
spring:
  profiles: dev


---
server:
  port: 8087
  servlet:
    context-path: /ccc
spring:
  profiles: prod
```

## 8.配置环境优先级

1. `file:./config/`
2. `file:./`
3. `classpath:/config/`
4. `classpath:/`

优先级由高到第,并且对于重复的配置高优先级的配置会覆盖低优先级的配置,但是各个配置文件会形成互补配置

## 9.配置文件的加载路径

springboot应用启动的时候,默认需要加载配置文件

1. [Devtools global settings properties](https://docs.spring.io/spring-boot/docs/2.1.2.RELEASE/reference/htmlsingle/#using-boot-devtools-globalsettings) on your home directory (`~/.spring-boot-devtools.properties` when devtools is active).
2. [`@TestPropertySource`](https://docs.spring.io/spring/docs/5.1.4.RELEASE/javadoc-api/org/springframework/test/context/TestPropertySource.html) annotations on your tests.
3. `properties` attribute on your tests. Available on [`@SpringBootTest`](https://docs.spring.io/spring-boot/docs/2.1.2.RELEASE/api/org/springframework/boot/test/context/SpringBootTest.html) and the [test annotations for testing a particular slice of your application](https://docs.spring.io/spring-boot/docs/2.1.2.RELEASE/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-tests).
4. **Command line arguments.** =>java -jar springboot_init-0.0.1-SNAPSHOT.jar --spring.config.location=D:\
5. Properties from `SPRING_APPLICATION_JSON` (inline JSON embedded in an environment variable or system property).
6. `ServletConfig` init parameters.
7. `ServletContext` init parameters.
8. JNDI attributes from `java:comp/env`.
9. Java System properties (`System.getProperties()`).
10. OS environment variables.
11. A `RandomValuePropertySource` that has properties only in `random.*`.
12. **[Profile-specific application properties](https://docs.spring.io/spring-boot/docs/2.1.2.RELEASE/reference/htmlsingle/#boot-features-external-config-profile-specific-properties) outside of your packaged jar (`application-{profile}.properties` and YAML variants).**
13. **[Profile-specific application properties](https://docs.spring.io/spring-boot/docs/2.1.2.RELEASE/reference/htmlsingle/#boot-features-external-config-profile-specific-properties) packaged inside your jar (`application-{profile}.properties` and YAML variants).**
14. **Application properties outside of your packaged jar (`application.properties` and YAML variants).**
15. **Application properties packaged inside your jar (`application.properties` and YAML variants).**
16. [`@PropertySource`](https://docs.spring.io/spring/docs/5.1.4.RELEASE/javadoc-api/org/springframework/context/annotation/PropertySource.html) annotations on your `@Configuration` classes.
17. Default properties (specified by setting `SpringApplication.setDefaultProperties`).

 

# 二. SpringBoot Web开发

1. 创建项目,选择需要的模块、场景
2. 自动导入当前场景下的一些组件,并且自动配置
3. 只需要编写业务即可

springboot给我们自动配置的组件相关的配置如何修改?在哪修改?

xxxAutoConfiguration 自动配置组件

xxxProperties 配置属性类,用于向自动配置组件提供相关的配置

## 1.SpringBoot对静态资源的处理

```java
public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
            } else {
                Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
                CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
                if (!registry.hasMappingForPattern("/webjars/**")) {
                    this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
                }

                String staticPathPattern = this.mvcProperties.getStaticPathPattern();
                if (!registry.hasMappingForPattern(staticPathPattern)) {
                    this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
                }

            }
        }
```

> 1.对/webjars/**处理

对于/webjars/** 所有的请求,都会在classpath:/META-INF/resources/webjars/找资源

webjars:通过jar包的方式添加静态资源文件

https://www.webjars.org/

http://localhost:8082/webjars/jquery/3.3.1/jquery.js

> 2.对/**处理

对于/**所有请求,都会到以下位置查找资源

```
classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
```

修改默认静态资源目录(一般不建议)

```pro
# 指定静态资源目录
# spring.resources.static-locations=classpath:/hello
# 如果修改后,则默认静态资源呢目录将会被覆盖
```

> 3.欢迎页

```java
private Optional<Resource> getWelcomePage() {
            String[] locations = getResourceLocations(this.resourceProperties.getStaticLocations());
    //classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
            return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
        }

        private Resource getIndexHtml(String location) {
            return this.resourceLoader.getResource(location + "index.html");
        }
```

springboot默认会在静态资源目录中查找index.html作为欢迎页

> 4.favicon图标配置

springboot默认会在静态资源目录中查找favicon.ico作为图标

## 2.  模板引擎

JSP、FreeMarker、Thymeleaf...(性能由高到低)

### 2.1 SpringBoot集成Thymeleaf

具体使用参考文档:

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

> 添加Thymeleaf启动器

```xml
<!--添加thmeleaf启动器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
```

> 编写页面模板

```java
private static final Charset DEFAULT_ENCODING;
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";
    private boolean checkTemplate = true;
    private boolean checkTemplateLocation = true;
    private String prefix = "classpath:/templates/";
    private String suffix = ".html";
    private String mode = "HTML";
```

页面模板默认前缀是"classpath:/templates/"

默认后缀是.html

在html标签上添加命名空间 xmlns:th="http://www.thymeleaf.org" => 提示

```html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户列表</title>
</head>
<body>
当前用户:
<div th:text="${name}"></div>
</body>
</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_无往而不胜_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值