第三章SpringBoot配置文件

什么是配置文件

  • 首先我们知道我们的程序是 指令 + 指令要处理的数据(变量,对象,数据库的记录…)
  • 假如我们所有的数据都是固定的情况下,那我们的程序无论允许多少次,结果都是一样的

img 随着我们的软件规模开始变大,数据来源不在唯一(数据不一定是写死在程序中了)

//数据写死了,执行多少才都不会变化
System.out.println("hello world");
//由于引入了外部的数据,所以可能每次输出的结果不一样
Scanner sc=new Scanner(System.in);
String target=sc.nextLine();
System.out.println(target);
  • 外部数据不仅仅局限于读取用户输入这种形态,会有其他形式,比如读取文件的内容,也比如读取数据库的内容,这样给了允许软件的用户可以在运行期间去修改程序依赖数据的权利

比如我们的QQ的配置文件

img

  • 这些分离出来的数据,有一部分是影响软件执行的逻辑发策略数据,一般我们把这类数据称为配置文件
  • 配置文件在GUI中是更常见的形式——软件的设置,就比如上面QQ的设置,其原理就是通过图形化的界面修改了硬盘上的配置文件

配置文件作用

  • 整个项目中所有重要的数据都是在配置文件中配置的,比如:
  • 数据库的连接信息(包含用户名和密码的设置);
  • 项目的启动端口;
  • 第三方系统的调用秘钥等信息;
  • 用于发现和定位问题的普通日志和异常日志等。

想象一下如果没有配置信息,那么 Spring Boot 项目就不能连接和操作数据库,甚至是不能保存可以用于排查问题的关键日志,所以配置文件的作用是非常重要的。

SpringBoot配置文件的格式

SpringBoot使用一个全局的配置文件 , 配置文件名称是固定的application.properties

Spring Boot 配置文件主要分为以下两种格式

  • .properties
  • .yml

image-20230214012056586

我们创建的SpringBoot项目默认是给的是application.properties

  • 这就好像连锁店里面的统一服装一样,有两种不同的款式,properties 类型的配置文件就属于老款“服饰”,也是创建 Spring Boot 项目时默认的文件格式(主要是由于仓库里还有库存),而 yml 属于新版款式,如果用户了解情况直接指定要新款服饰,那么就直接发给他。

特殊说明

  • 理论上讲 properties 可以和 yml 一起存在于一个项目当中,当 properties 和 yml 一起存在一个项目中时,如果配置文件中出现了同样的配置,比如 properties 和 yml 中都配置了“server.port”,那么这个时候会以 properties 中的配置为主,也就是** .properties 配置文件的优先级最高,但加载完 .properties 文件之后,也会加载 .yml 文件的配置信息**。

  • 虽然理论上来讲 .properties 可以和 .yml 共存,但实际的业务当中,我们通常会采取一种统一的配置文件格式,这样可以更好的维护(降低故障率)。这就好像连锁店的服饰一样,不管是老款的服装还是新款的服装,一定要统一了才好看。

properties 配置文件说明

properties 配置文件是最早期的配置文件格式,也是创建 Spring Boot 项目默认的配置文件。

properties 基本语法

properties 是以键值的形式配置的,key 和 value 之间是以“=”连接的,如:

#配置我们服务器的
server.port=8888

PS:小技巧:配置文件中使用“#”来添加注释信息。

properties 缺点分析

  • priperties默认是不支持中文显示,所以最好不写中文
  • 这种文件也不会有自动提醒,需要安装插件才会有
  • properties 配置文件中会有很多的冗余的信息
# 配置项目端口号
server.port=8084
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/testdb?characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123

yml 配置文件

yml概述

  • yml 是 YMAL 是缩写,它的全称 Yet Another Markup Language 翻译成中文就是“另一种标记语言”。yml 是一个可读性高,易于理解,用来表达数据序列化的格式。它的语法和其他高级语言类似,并且可以简单表达清单(数组)、散列表,标量等数据形态。它使用空白符号缩进和大量依赖外观的特色,特别适合用来表达或编辑数据结构、各种配置文件等。yml 最大的优势是可以跨语言,不止是 Java 中可以使用 golang、python 都可以使用 yaml 作为配置文件。
  • 这种语言以数据作为中心,而不是以标记语言为重点!

以前的配置文件,大多数都是使用xml来配置;比如一个简单的端口配置,我们来对比下yml和xml

传统xml配置

<server>
	<port>8081<port>
</server>

yml配置

server:
	prot: 8080

yml基础语法

k-v键值对

# k-v键值对
name: xiaoqi
#相当于name=xiaoqi
# 存对象
student:
  name: xiaoqi
  age: 12
  
# 行内写法
student1: {name: xiaoqi,age: 13}

#数组
pets:
  - cat
  - dog
  - pyg

pets1: [cat,dog]

yml 是树形结构的配置文件,它的基础语法是“key: value”,注意 key 和 value 之间使用英文冒汗加空格的方式组成的,其中的空格不可省略

说明:语法要求严格!

  • 空格不能省略
  • 以缩进来控制层级关系,只要是左边对齐的一列数据都是同一个层级的。
  • 属性和值的大小写都是十分敏感的。

字面量:普通的值 [ 数字,布尔值,字符串 ]

字符串默认不用加上单引号或者双引号, 字符串默认不用加上双引号或者单引号;

注意:

  • “ ” 双引号,不会转义字符串里面的特殊字符 , 特殊字符会作为本身想表示的意思;

    • 比如 :name: “kuang \n shen” 输出 :kuang 换行 shen
  • ‘ ’ 单引号,会转义特殊字符 , 特殊字符最终会变成和普通字符一样输出

    • 比如 :name: ‘kuang \n shen’ 输出 :kuang \n shen

yml 和 properties 连接数据库的配置对比

spring:
datasource:
url: jdbc:mysql://127.0.0.0:3306/dbname?characterEncoding=utf8
username: root
password: root  

读取配置文件

如果在项目中,想要主动的读取配置文件中的内容,可以使用 @Value 注解来实现。

@Value 注解使用“${}”的格式读取

application.properties

#user对象的属性
user:
  id: 2
  pwd: 留守处123
@Component
public class User {
     @Value("${user.id}")
    private Integer id;
    @Value("${user.pwd}")
    private String pwd; 
    对应的getter setter 构造方法
	.....
	.....
	.....
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

测试

@SpringBootApplication
public class Boot03ConfigApplication {

	public static void main(String[] args) {
		ConfigurableApplicationContext run = SpringApplication.run(Boot03ConfigApplication.class, args);
		User user = run.getBean(User.class);
		System.out.println(user);
	}

}
//输出结果
User{id=1, name='lsc07'}

@ConfigurationProperties配置绑定

如何使用Java读取到properties文件中的内容,并且把它封装到JavaBean中,以供随时使用

#user对象的属性
user:
  id: 2
  pwd: 留守处123
@Component
@ConfigurationProperties( prefix = "user")
public class User {
    private Integer id;
    private String pwd;

    public User() {
    }

    public User(Integer id, String pwd) {
        this.id = id;
        this.pwd = pwd;
    }

    public Integer getId() {
        return id;
    }

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

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

加载指定的配置文件

**@PropertySource :**加载指定的配置文件;

@configurationProperties:默认从全局配置文件中获取值;

我们去在resources目录下新建一个person.properties文件

name=lsc

然后在我们的代码中指定加载person.properties文件

@PropertySource(value = "classpath:person.properties")
@Component //注册bean
public class Person {
    @Value("${name}")
    private String name;
    ......  }

小结

  • @ConfigurationProperties只需要写一次即可 , @Value则需要每个字段都添加
  • 松散绑定:这个什么意思呢? 比如我的yml中写的last-name,这个和lastName是一样的, - 后面跟着的字母默认是大写的。这就是松散绑定。可以测试一下
  • JSR303数据校验 , 这个就是我们可以在字段是增加一层过滤器验证 , 可以保证数据的合法性
  • 复杂类型封装,yml中可以封装对象 , 使用value就不支持

JSR303数据校验

空检查
@Null 验证对象是否为null
@NotNull 验证对象是否不为null, 无法查检长度为0的字符串
@NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty 检查约束元素是否为NULL或者是EMPTY.

Booelan检查
@AssertTrue 验证 Boolean 对象是否为 true
@AssertFalse 验证 Boolean 对象是否为 false

长度检查
@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内
@Length(min=, max=) Validates that the annotated string is between min and max included.

日期检查
@Past 验证 Date 和 Calendar 对象是否在当前时间之前,验证成立的话被注释的元素一定是一个过去的日期
@Future 验证 Date 和 Calendar 对象是否在当前时间之后 ,验证成立的话被注释的元素一定是一个将来的日期
@Pattern 验证 String 对象是否符合正则表达式的规则,被注释的元素符合制定的正则表达式,regexp:正则表达式 flags: 指定 Pattern.Flag 的数组,表示正则表达式的相关选项。

数值检查
建议使用在Stirng,Integer类型,不建议使用在int类型上,因为表单值为“”时无法转换为int,但可以转换为Stirng为”“,Integer为null
@Min 验证 Number 和 String 对象是否大等于指定的值
@Max 验证 Number 和 String 对象是否小等于指定的值
@DecimalMax 被标注的值必须不大于约束中指定的最大值. 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.小数存在精度
@DecimalMin 被标注的值必须不小于约束中指定的最小值. 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.小数存在精度
@Digits 验证 Number 和 String 的构成是否合法
@Digits(integer=,fraction=) 验证字符串是否是符合指定格式的数字,interger指定整数精度,fraction指定小数精度。
@Range(min=, max=) 被指定的元素必须在合适的范围内
@Range(min=10000,max=50000,message=”range.bean.wage”)
@Valid 递归的对关联对象进行校验, 如果关联对象是个集合或者数组,那么对其中的元素进行递归校验,如果是一个map,则对其中的值部分进行校验.(是否进行递归验证)
@CreditCardNumber信用卡验证
@Email 验证是否是邮件地址,如果为null,不进行验证,算通过验证。
@ScriptAssert(lang= ,script=, alias=)
@URL(protocol=,host=, port=,regexp=, flags=)]()]()

@Component
@ConfigurationProperties(prefix = "person")
@Validated//开启数据验证
public class Person {
    @Email(message = "这是验证数据是不是邮箱形式")
    private String name;
}

两个类型配置文件小结

  • properties 是以 key=value 的形式配置的键值类型的配置文件,而 yml 使用的是类似 json 格式的树形配置方式进行配置的,yml 层级之间使用换行缩进的方式配置,key 和 value 之间使用“: ”英文冒号加空格的方式设置,并且空格不可省略。
  • properties 为早期并且默认的配置文件格式,但其配置存在一定的冗余数据,使用 yml 可以很好的解决数据冗余的问题。
  • yml 通用性更好,支持更多语言,如 Java、Go、Python 等,如果是云服务器开发,可以使用一份配置文件作为 Java 和 Go 的共同配置文件。
  • yml 虽然可以和 properties 共存,但一个项目中建议使用统一的配置类型文件

多环境配置和配置切换

配置文件加载位置

外部加载配置文件的方式十分多,我们选择最常用的即可,在开发的资源文件中进行配置!

官方外部配置文件说明参考文档

image-20230214024353554

springboot 启动会扫描以下位置的application.properties或者application.yml文件作为Spring boot的默认配置文件:

优先级1:项目路径下的config文件夹配置文件优先级
优先级2:项目路径下配置文件优先级
优先级3:资源路径下的config文件夹配置文件优先级
优先级4:资源路径下配置文件

image-20230214024817036

优先级由高到底,高优先级的配置会覆盖低优先级的配置;

SpringBoot会从这四个位置全部

加载主配置文件;互补配置;

多环境切换

  • profile是Spring对不同环境提供不同配置功能的支持,可以通过激活不同的环境版本,实现快速切换环境;

多配置文件
我们在主配置文件编写的时候,文件名可以是 application-{profile}.properties/yml , 用来指定多个环境版本;

例如:

  1. application-test.properties 代表测试环境配置
  2. application-dev.properties 代表开发环境配置

但是Springboot并不会直接启动这些配置文件,它默认使用application.properties主配置文件;

我们需要通过一个配置来选择需要激活的环境:

#比如在配置文件中指定使用dev环境,我们可以通过设置不同的端口号进行测试;
#我们启动SpringBoot,就可以看到已经切换到dev下的配置了;
spring.profiles.active=dev

yaml的多文档块

和properties配置文件中一样,但是使用yml去实现不需要创建多个配置文件,更加方便了 !

spring:
  profiles:
    active: dev
server:
  port: 8081
---
server:
  port: 8082
Spring:
  profiles: dev #命名

---
server:
  port: 8083

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: Spring Boot整合MyBatis的配置文件主要包括以下几个方面: 1. 数据库连接配置 在application.properties或application.yml中配置数据库连接信息,包括数据库URL、用户名、密码等。 2. MyBatis配置 在application.properties或application.yml中配置MyBatis的相关配置,包括Mapper扫描路径、MyBatis配置文件路径等。 3. 数据源配置 在Spring Boot中,可以使用自带的数据源或者第三方数据源,如Druid、HikariCP等。需要在配置文件中配置数据源相关信息。 4. Mapper配置 在MyBatis中,需要配置Mapper接口和Mapper.xml文件的对应关系。可以使用@MapperScan注解或者在MyBatis配置文件中配置。 以上是Spring Boot整合MyBatis的主要配置文件内容,具体实现可以参考Spring Boot官方文档或者相关教程。 ### 回答2: Spring Boot是一个基于Spring框架的快速开发Java Web应用的工具。而Mybatis是一个优秀的持久层框架。在实际开发中,很多项目会将Spring Boot和Mybatis集成起来使用,这样可以使开发更加高效,代码更加简洁。下面我将介绍Spring Boot整合Mybatis的配置步骤。 1.添加依赖 在pom.xml中加入Spring Boot和Mybatis的依赖。 ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.6</version> </dependency> ``` 2.设置数据源 在application.properties中设置数据源参数,包括数据库名称、用户名、密码等等。 ``` spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&autoReconnect=true spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 3.配置Mybatis 在resources目录下新建mybatis文件夹,在其中创建一些必要的配置文件,如SqlMapper.xml、mybatis-config.xml、Application.yml等。 a、SqlMapper.xml 配置连接mysql并定义Mapper操作的SQL语句,可以通过namespace来设置映射接口。在这里我们可以看到它是里面是调用的映射接口 ID。 ``` <?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.nian.springboot.mapper.StudentMapper"> <select id="selectByPrimaryKey" resultType="com.nian.springboot.pojo.Student"> select * from student where id = #{id,jdbcType=INTEGER} </select> </mapper> ``` b、mybatis-config.xml mybatis-config.xml用于配置Mybatis相关信息。 ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="logImpl" value="LOG4J"/> </settings> <typeAliases> <typeAlias type="com.nian.springboot.pojo.Student" alias="Student"/> </typeAliases> <mappers> <mapper resource="mapper/StudentMapper.xml"/> </mappers> </configuration> ``` c、Application.yml 在resources目录下新建application.yml文件,用于设置Spring Boot应用程序的配置,包括服务器端口、运行环境等。 ``` spring: servlet: multipart: max-file-size: 10MB max-request-size: 100MB async: request-timeout: 60000 datasource: url: jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false username: root password: root driver-class-name: com.mysql.jdbc.Driver mybatis: config-location: classpath:mybatis/mybatis-config.xml mapper-locations: classpath*:mapper/**/*.xml type-aliases-package: com.nian.springboot.pojo ``` 4.创建mapper 创建mapper文件夹,并创建映射接口,如StudentMapper.java。 ``` public interface StudentMapper { Student selectByPrimaryKey(Integer id); } ``` 5.创建entity 创建实体类,映射数据库中的表,如Student.java。 ``` public class Student { private Integer id; private String name; private Integer age; private String sex; //getter setter } ``` 6.创建service 创建service,实现业务逻辑,如StudentService.java。 ``` @Service public class StudentService { @Autowired private StudentMapper studentMapper; public Student selectByPrimaryKey(Integer id) { return studentMapper.selectByPrimaryKey(id); } } ``` 7.创建Controller 创建Controller接口,处理请求,如StudentController.java。 ``` @RestController @RequestMapping("/student") public class StudentController { @Autowired private StudentService studentService; @RequestMapping(value = "/selectByPrimaryKey", method = RequestMethod.GET) public Student selectByPrimaryKey(@RequestParam("id") Integer id) { return studentService.selectByPrimaryKey(id); } } ``` 以上就是Spring Boot整合Mybatis的大致步骤,当然,具体实现跟业务有关。可以先按照这个框架搭建结构,再根据具体业务逻辑进行扩展和修改。整合后,我们就可以用Spring Boot和Mybatis在数据库中进行数据的 CRUD(增删改查) 操作了。 ### 回答3: Spring Boot 是一个基于 Spring 框架的快速开发框架,它具有简单、快速、灵活等优点,可用于快速搭建 Web 应用程序。MyBatis 是一款优秀的持久化框架,可以帮助开发者简化 DAO 层的开发。在实际的项目中,常常需要将 Spring Boot 与 MyBatis 结合起来使用,以帮助实现数据的持久化操作。本文将向读者介绍 Spring Boot 如何整合 MyBatis 的配置文件。 1. 添加依赖 首先,需要在 pom.xml 文件中添加 MyBatis 和数据库驱动程序的依赖。常用的数据库驱动程序有 MySQL、Oracle 等,具体的依赖信息可以在 Maven 仓库中查找。在 pom.xml 中添加如下代码: ``` <dependencies> <!-- MyBatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency> <!-- MySQL 驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.48</version> </dependency> </dependencies> ``` 2. 配置数据源 在 Spring Boot 中,可以使用 application.properties 或 application.yml 的配置文件来配置数据源。需要注意的是,数据源的配置需要放在 Spring Boot 的自动配置类上方,以便在 MyBatis 配置文件中使用。这里以 MySQL 数据库为例,配置如下: ``` spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 3. 配置 MyBatis 在 Spring Boot 集成 MyBatis 的过程中,还需要配置 MyBatis 的相关参数,例如 MyBatis 的 mapper、configuration 等。Spring Boot 通过扫描指定的包来自动装配 mapper,并且 MyBatis 的配置文件 mybatis-config.xml 可以省略。在 application.properties 或 application.yml 中添加 MyBatis 相关配置: ``` mybatis.mapper-locations=classpath*:mapper/*.xml mybatis.configuration.map-underscore-to-camel-case=true mybatis.configuration.cache-enabled=true ``` 4. 创建 mapper 接口和实体类 在 Spring Boot 中,可以使用注解方式来声明 mapper 接口和实体类。在 mapper 接口上加上`@Mapper` 注解,在实体类上加上`@TableName` 注解即可: ``` @Mapper public interface UserMapper { @Select("select * from user where id=#{userId}") User findUserById(int userId); } @Data @TableName(value = "user") public class User { @TableId(value = "id",type = IdType.AUTO) private Integer id; private String userName; private String password; } ``` 5. 测试 最后,在 controller 中引入 mapper 接口,即可调用其方法进行数据的操作: ``` @RestController public class UserController { @Autowired private UserMapper userMapper; @RequestMapping("/user/{userId}") public User getUserById(@PathVariable int userId){ User user=userMapper.findUserById(userId); return user; } } ``` 以上是 Spring Boot 整合 MyBatis 的配置方法,通过这种方式可以快速地实现对数据库的操作。同时,Spring Boot 还集成了其他的数据库操作框架,如 JPA、Hibernate 等,读者可以根据需要选择使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

库里不会投三分

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

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

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

打赏作者

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

抵扣说明:

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

余额充值