SpringBoot学习笔记二之SpringBoot基础配置

147 阅读5分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第18天,点击查看活动详情

基础配置

1、配置文件格式

image.png

SpringBoot配置文件加载顺序(了解): application.properties > application.yml > application.yaml

注意:SpringBoot 程序的配置文件名必须是 application ,只是后缀名不同而已。

自动提示功能消失解决方案: image.png

2、yaml格式

image.png

YAML (YAML Ain't Markup Language) ,一种数据序列化格式
优点容易阅读(清爽)、容易与脚本语言交互以数据为核心,重数据轻格式
YAML文件扩展名yml(主流)、yaml

yaml语法规则

  1. 大小写敏感
  2. 属性层级关系使用多行描述,每行结尾使用冒号结束
  3. 使用缩进表示层级关系,同层级左侧对齐,只允许使用空格(不允许使用Tab键)
  4. 属性值前面添加空格(属性名与属性值之间使用冒号 + 空格作为分隔)
  5. 表示注释

yaml数组数据

  • 数组数据在数据书写位置的下方使用减号作为数据开始符号,每行书写一个数据,减号与数据间空格分隔(使用的并不是很多,了解下就好)
enterprise:
  name: itcast
  age: 16
  tel: 4006184000
  subject:
    - Java
    - 前端
    - 大数据

3、yaml配置文件数据读取的三种方式

application.yml配置信息

lesson: SpringBoot

server:
  port: 80

enterprise:
  name: kaf
  age: 18
  tel: 1234567890
  subject:
    - Java
    - 前端
    - 大数据

1. 读取yml配置数据

读取配置文件方式读取数据

普通的读取yml配置数据的方式(这种方式太繁琐了!每次要使用的时候都要单独引入

image.png

package com.kaf.controller;

import org.springframework.beans.factory.annotation.Value;
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 // @Controller + @ResponseBody(不进行跳转)
@RequestMapping("/books")
public class BookController {
    @Value("${lesson}")
    private String lesson;
    @Value("${enterprise.name}")
    private String name;
    @Value("${enterprise.subject[1]}")
    private String subject;


    @GetMapping("/{id}")
    public String getById(@PathVariable Integer id){
        System.out.println(lesson);
        System.out.println(name);
        System.out.println(subject);
        return "hello, spring boot";
    }
}

2. Environment对象

使用Spring内置的Environment对象读取数据

SpringBoot 还提供了一种使用 @Autowired 注解注入 Environment 对象来读取数据的方法。 image.png

package com.kaf.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
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 // @Controller + @ResponseBody(不进行跳转)
@RequestMapping("/books")
public class BookController {
    @Value("${lesson}")
    private String lesson;
    @Value("${enterprise.name}")
    private String name;
    @Value("${enterprise.subject[1]}")
    private String subject;

    @Autowired
    private Environment environment;

    @GetMapping("/{id}")
    public String getById(@PathVariable Integer id){
        System.out.println(lesson);
        System.out.println(name);
        System.out.println(subject);
        System.out.println("---------");
        System.out.println(environment.getProperty("lesson"));
        System.out.println(environment.getProperty("enterprise.name"));
        System.out.println(environment.getProperty("enterprise.subject[2]"));
        return "hello, spring boot";
    }
}

这种方式 SpringBoot 会将配置文件中所有的数据封装到 Environment 对象中,如果需要使用哪个数据,只需要通过调用 Environment 对象的 getProperty(String name) 方法获取。

PS:这种方式是遍历yml配置文件中的所有数据,然后将其放到Environment对象中,等需要使用的时候再进行提取的一种方式。

3. 自定义对象

将数据封装到自定义对象中以此来读取数据

SpringBoot 还提供了将配置文件中的数据,封装到我们自定义的实体类对象中的方式。

image.png

  • 将实体类 bean 的创建交给 Spring 管理。 在自定义对象类上==添加 @Component 注解==
  • ==使用 @ConfigurationProperties 注解==表示==加载配置文件== 在该注解中也可以 ==使用 prefix 属性指定只加载指定前缀的数据==
  • 在 BookController(控制层) 中进行注入

image.png

package com.kaf.domian.domain;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component // 将该实体类交给Spring容器创建并管理
@ConfigurationProperties(prefix = "enterprise") //加载配置文件(prefix: 加载指定前缀的数据 即 application.yml下的enterprise数据)
public class Enterprise {
    private String name;
    private int age;
    private String tel;
    private String[] subject;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String[] getSubject() {
        return subject;
    }

    public void setSubject(String[] subject) {
        this.subject = subject;
    }

    @Override
    public String toString() {
        return "Enterprise{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", tel='" + tel + '\'' +
                ", subject=" + Arrays.toString(subject) +
                '}';
    }
}
Output:
    Enterprise{name='kaf', age=18, tel='1234567890', subject=[Java, 前端, 大数据]}

小问题: image.png

这个警告提示的解决方案是在 pom.xml 中添加如下依赖即可

		<!--解决自定义对象在读取配置属性时的警告问题(其实不配置也没啥问题...)-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>

4、多环境配置

当项目开发完毕后要上线就需要使用另一个环境,如:将环境的配置改为线上环境

以下将讨论:如何在一个配置文件中制作出多个环境,同时让这些环境都能够切换使用

不同类型的配置文件,所配置的多环境开发都不相同

1. 使用yaml文件配置多环境的方式

image.png

image.png

# 使用yaml文件配置多环境的方式
#设置启用的环境
spring:
  profiles:
    active: dev

---
spring:
  profiles: dev
server:
  port: 80
---
#生产
spring:
  profiles: pro #给生产环境起的名字
server:
  port: 81
---
#测试
spring:
  profiles: test #给测试环境起的名字
server:
  port: 82
---

PS:在 application.yml 中是使用 --- 来分割不同的配置
注意 如果还要在上述配置信息中再添加内容的话,就需要在最后面的配置信息加上 "---"

2. 使用properties文件配置多环境的方式

properties 类型的配置文件,在配置多环境时需要定义不同的配置文件

image.png

==SpringBoot 只会默认加载名为 application.properties 的配置文件==,所以需要在 application.properties 配置文件中设置启用哪个配置文件

3. 命令行启动参数设置

PS:使用 SpringBoot 开发的程序以后都是打成 jar 包的

当我们使用package指令进行打包的时候,打包出来的jar包已经固定环境了,这该这么处理呢? SpringBoot 提供了在运行 jar 包时,设置开启指定的临时环境的方式(以此来解决上述问题),如下

  • 指定临时切换的环境:java –jar xxx.jar –-spring.profiles.active=test
  • 指定临时修改端口号:java –jar xxx.jar –-server.port=88
  • 也可同时配置:java –jar springboot.jar –-server.port=88 –-spring.profiles.active=test

image.png

4. 多环境开发兼容问题

由上述可知,SpringBoot也有多环境开发,然后Mave也有🙄。这时就要考虑,使用的时候哪一个的环境的问题(多环境开发控制问题)

由于我们在将项目打包成jar包时,使用的是maven指令来执行的。所以在进行多环境开发时,应该以maven为主,boot为辅的原则进行多环境控制

<!-- pom.xml -->
	<profiles>
		<!--开发环境-->
		<profile>
			<id>dev</id>
			<properties>
				<profile.active>dev</profile.active>
			</properties>
		</profile>

		<!--生产环境-->
		<profile>
			<id>pro</id>
			<properties>
				<profile.active>pro</profile.active>
			</properties>
			<!-- 设置默认启动时的环境为: pro生产环境 -->
			<activation>
				<activeByDefault>true</activeByDefault>
			</activation>
		</profile>

		<!--测试环境-->
		<profile>
			<id>test</id>
			<properties>
				<profile.active>test</profile.active>
			</properties>
		</profile>
	</profiles>
	
<!-- 注意要配置解析占位符的插件!!! -->
		<plugins>
			<!--TODO 对资源文件进行处理的一个插件: 主要是进行占位符("${}")的解析操作 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
				<version>3.2.0</version>
			</plugin>
		</plugins>
	

<!-- application.yml -->
# 设置启用的环境
spring:
  profiles:
    active: ${profile.active}
---
server:
  port: 80
spring:
  config:
    activate:
      on-profile: dev
---
#生产
spring:
  profiles: pro #给生产环境起的名字
server:
  port: 81
---
#测试
spring:
  profiles: test #给测试环境起的名字
server:
  port: 82
---
# 表示以Maven为主,Boot为辅的思想

最后打包将以Maven定义的为主 即为pro版本的项目

PS:使用 maven-resources-plugin 插件的目的:解析占位符(${})

5、配置文件分类

由于测试人员在进行测试的时候,很多配置都与开发环境不同,所以测试人员在进行测试的时候需要进行很多临时的修改。如果还像之前那样在命令行窗口进行修改的话,很麻烦。SpringBoot提供了一种方式来进行简便处理

SpringBoot 定义了配置文件放置在不同的位置所获得的优先级也不同,具体如下:

  • 1级:classpath:application.yml
  • 2级:classpath:config/application.yml
  • 3级:file :application.yml
  • 4级:file :config/application.yml 优先级从低到高

类路径classpath指:在开发过程中项目的路径(简单理解为:在项目文件夹下的路径)
文件路径file指:jar包所在的路径