[023-5].第5节:SpringBoot的配置文件

我的后端学习大纲

SpringBoot学习大纲


1.配置文件:

1.1.配置文件概述:

  • 1.SpringBoot默认是使用两个类型的文件作为`全局配置文件
    • application.properities
    • application.yml
  • 2.默认properities类型的文件优先升级高于yml类型的配置文件;最好就只写一种类型的配置文件
  • 3.配置文件的作用就是:通过修改配置文件我们就可以修改SpringBoot自动配置的默认值;如修改默认端口号,修改启动时的banner图,日志的级别,默认是info级别;
    • 修改服务器端口:server.port=80
    • 设置应用的访问contextpath:server.servlet.context-path=/boot
    • 关闭运行日志图标(banner):spring.main.banner-mode=off
    • 设置日志相关:logging.level.root=debug
    • SpringBoott的内置属性查询或者去官方文档中参考文档第一项:Application Properties
  • 4.SpringBoot中导入对应starter后,才提供上述对应的配置属性,书写SpringBoot配置采用关键字+提示形式书写
  • 5.配置文件的优先级如下:
    • SpringBoot配置文件加载顺序:application.properties > application.yml > application.yaml ;当properties 存在的时候,其他格式的配置文件相同的配置时不生效;在 SpringBoot2.4 开始, 当两种格式配置文件同时存在,使用的是 yml 配置文件.
    • 不同的配置文件中相同的配置按照优先级相互覆盖,不同配置文件中不同配置全部保留;
  • 6.置文件的位置:配置文件放在src/main/resources目录下面或者类路径/configx下面

1.2.多环境配置:

  • 1.在实际开发的过程中,我们的项目会经历很多的阶段(开发->测试->上线),每个阶段的配置也会不同例如:端口、上下文根、数据库等,那么这个时候为了方便在不同的环境之间切换,SpringBoot 提供了多环境配置,具体步骤如下为每个环境创建一个配置文件,命名必须以 application-环境标识.properties|yml
    • 创建开发环境的配置文件: application-dev.properties( application-dev.yml )
    #测试使用的配置文件
    server:
      port: 9001
      servlet:
        context-path: /mytest
    
    • 创建测试者使用的配置: application-test.properties
    #开发环境的配置文件
    server:
      port: 8081
      servlet:
        context-path: /mydev
    
    • 创建上线环境使用的配置: application-test.properties
    #项目上线使用的配置文件
    server:
      port: 9002
      servlet:
        context-path: /myonline
    
  • 2.配置激活使用哪个配置:
    在这里插入图片描述

2.YAML语法

2.1.概述:

  • 1.YAML是一种数据序列化格式
  • 2.它是以数据为中心
  • 3.容易阅读,容易与脚本语言交互,如下图所示:
    在这里插入图片描述

2.2.YAML基本语法

  • 1.key: value:kv之间有空格
  • 2.使用缩进表示层级关系
  • 3.缩进时候不可以使用tab键。只可以使用空格
  • 4.缩进的空格数量不重要,重要的是相同层级的元素只要在缩进后可以齐就可以。
  • 5.属性和值中:大小写敏感
  • 6.#表示注释
  • 7.字符串不需要加引号,单引号会将\n作为字符串输出双引号会将\n作为换行输出,双引号会改变它的行为,作为换行。单引号不会改变它的行为。双引号会转义,单引不号会转义

2.3.数据类型

  • 1.字面量:单个的、不可再分的值。date、boolean、string、number、null
k: v

在这里插入图片描述

  • 2.对象:键值对的集合。map、hash、set、object
行内写法:  k: {k1:v1,k2:v2,k3:v3}
#或
 k: 
	k1: v1
    k2: v2
    k3: v3
  • 3.数组:一组按次序排列的值。array、list、queue
行内写法: 
 k: [v1,v2,v3]
#或者
k:
 - v1
 - v2 - v3

在这里插入图片描述

2.4.yml中的自定义配置与读取配置文件中数据

  • 1.自定义配置:SpringBoot 的核心配置文件中,除了使用内置的配置项之外,我们还可以在自定义配置,然后采用如下注解去读取配置的属性值

a.举例1:@Value 注解的使用:

  • 1.自定义配置文件:
server.port=9090
server.servlet.context-path=/myboot
school.name=动力节点
school.address=北京大兴区
school.website=www.bjpowernode.com
site=www.bjpowernode.com
  • 2.编写controllere,使用@Value("${key}") :key 来自 application.properties(yml)来获取数据
package com.bjpowernode.controller;

import com.bjpowernode.vo.SchoolInfo;
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;

import javax.annotation.Resource;

@Controller
public class HelloController {
    @Value("${server.port}")
    private Integer port;

 	@Value("${subject[1]}")
    private Integer qianduan;
    
	@Value("${users[1].age}")
    private Integer qianduan;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${school.name}")
    private String name;

    @Value("${site}")
    private String site;

    @Resource
    private SchoolInfo info;

    @RequestMapping("/data")
    @ResponseBody
    public String  queryData(){
        return name+",site="+site+", 项目的访问地址="+contextPath+",使用的端口="+port;
    }

    @RequestMapping("/info")
    @ResponseBody
    public String  queryInfo(){
        return "SchoolInfo对象=="+info.toString();
    }
}

在这里插入图片描述
在这里插入图片描述

b.举例2:读取单独属性的值:

  • 1.yaml文件编写:
    在这里插入图片描述
  • 2.java读取配置文件中单一属性值
    在这里插入图片描述
    在这里插入图片描述

c.举例3:@ConfigurationProperties 注解和@Value注解(properities配置文件形式):

  • 1.自定义配置文件:
server.port=9090
server.servlet.context-path=/myboot
school.name=动力节点
school.address=北京大兴区
school.website=www.bjpowernode.com
site=www.bjpowernode.com
  • 2.定义实体类:SchoolInfo,使用 @ConfigurationProperties注解,把配置文件中的属性注入;这种方式注入的话,就比上面按照字段一个一个的注入要方便很多;
package com.bjpowernode.vo;

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

@Component
@ConfigurationProperties(prefix = "school")
public class SchoolInfo {

    private String name;

    private String website;

    private String address;


    public String getName() {
        return name;
    }

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

    public String getWebsite() {
        return website;
    }

    public void setWebsite(String website) {
        this.website = website;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "SchoolInfo{" +
                "name='" + name + '\'' +
                ", website='" + website + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

  • 3.创建 SchoolController:
@Controller
public class SchoolController {
	//创建对象
 	@Resource
 	private SchoolInfo schoolInfo;
 	
 	//接受到myschool请求
 	@RequestMapping("/myschool")
 	@ResponseBody
	public String doSchool(){
	//对象调方法,结果返回
 	return "学校信息:"+schoolInfo.toString();
   } 
}
  • 4.执行 Application , 访问浏览器查看数据

d.举例4:自定义对象封装指定数据(yml配置文件形式,常用):

  • 1.建一个java类,然后使用@ConfigurationProperties注解绑定配置信息到封装类中;使用@Component把封装类添加到Spring管理的bean容器中,否则无法进行属性注入,
===========Person.java===========
package com.jianqun.boot.bean;

import lombok.Data;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
/*
 * @author lvjianuqn
 * @create 2021-10--21:50
 * @ConfigurationProperties:指定要加载的数据
 */

@ConfigurationProperties(prefix = "person")
@Component
@Data
@ToString
public class Person {
    private String userName;
    private Boolean boss;
    private Date birth;
    private Integer age;
    private Anim pet;
    private String[] interests;
    private List<String> animal;
    private Map<String, Object> score;
    private Set<Double> salarys;
    private Map<String, List<Pet>> allPets;
}
  • 2.创建配置文件:application.yml
# yaml表示以上对象
===========application.yml===========
person:
  userName: zhangsan
  boss: false
  birth: 2019/12/12 20:12:33
  age: 18
  pet: 
    name: tomcat
    weight: 23.4
  interests: [篮球,游泳]
  animal: 
    - jerry
    - mario
  score:
    english: 
      first: 30
      second: 40
      third: 50
    math: [131,140,148]
    chinese: {first: 128,second: 136}
  salarys: [3999,4999.98,5999.99]
  allPets:
    sick:
      - {name: tom}
      - {name: jerry,weight: 47}
    health: [{name: mario,weight: 47}]
  • 3.创建controller,然后我们在浏览器中进行访问测试
    在这里插入图片描述

e.举例5:读取全部数据的方式2:

  • 1.步骤1:使用Environment对象封装全部配置信息
  • 2.步骤2:使用Autowired自动装配数据到Environment
    在这里插入图片描述

2.5.yml中的属性引用及配置文件中的注意事项:

a.什么是属性的引用:

  • 1.所谓的属性引用意思就是tempDir中,第一个路径的值和baseDir中的值有关系,会随之变化而变化,所以就用{}形式来进行引用:
    在这里插入图片描述

b.注意事项:

  • 1.当属性中如果出现了某些特殊的字符,就可以使用双引号包裹起来作为字符解析
    在这里插入图片描述

c.自定义类绑定的配置提示

  • 1.这是IDEA不识别配置文件的问题,自定义的类和配置文件绑定一般没有提示。如果想有提示,需要进行引入依赖,这样就可以解决这个提示的问题;当然不加依赖也不会影响程序的执行;
    在这里插入图片描述
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-configuration-processor</artifactId>
  <!--
   表示防止此依赖加载到其他模块
  --!>
  <optional>true</optional>
</dependency>
  • 2.依赖引入后,为了减少加载时间,需要告诉springBoot打包的时候,不要将processor依赖进行打包。所以需要进行以下配置
 <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-configuration-processor</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

2.6. SpringBoot 中使用 ApplicationContext来获取容器:

  • 1.在 main 方法中,SpringApplication.run()方法获取返回的 Spring 容器对象再获取业务 bean进行调用
    在这里插入图片描述

2.7.CommandLineRunner 接口和ApplicationRunner接口

开发中可能会有这样的情景:需要在容器启动后执行一些内容。比如读取配置文件,数据库连接之类的。
SpringBoot 给我们提供了两个接口来帮助我们实现这种需求。这两个接口分别为 CommandLineRunner 和 ApplicationRunner
他们的执行时机为容器启动完成的时候。这两个接口中有一个 run 方法,我们只需要实现这个方法即可。
这两个接口的不同之处在于: ApplicationRunner 中 run 方 法 的 参 数为ApplicationArguments , 而CommandLineRunner接口中 run 方法的参数为 String 数组

package com.bjpowernode;

import com.bjpowernode.service.HelloService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.util.ResourceUtils;

import javax.annotation.Resource;

@SpringBootApplication
public class Application implements CommandLineRunner {

	@Resource
	private HelloService helloService;

	public static void main(String[] args) {
		System.out.println("准备创建容器对象");
		//创建容器对象
		SpringApplication.run(Application.class, args);
		System.out.println("容器对象创建之后");
	}

	@Override
	public void run(String... args) throws Exception {
		String str  = helloService.sayHello("lisi");
		System.out.println("调用容器中的对象="+str);  
		//可做自定义的操作,比如读取文件, 数据库等等
		System.out.println("在容器对象创建好,执行的方法");
	}
}

3.配置文件说明:

3.1.配置文件修改默认配置

a.resources\application.properties 配置大全:

  • 1.SpringBoot 项目最重要也是最核心的配置文件就是 application.properties,所有的框架配置都可以在这个配置文件中说明
#SPRING CONFIG(ConfigFileApplicationListener)
spring.config.name =#配置文件名(默认 为 'application' )
spring.config.location =#配置文件的位置

# 多环境配置文件激活属性
spring.profiles.active=dev #加载 application-dev.properties 配置文件内容
application-dev.properties: #开发环境
application-test.properties: #测试环境
application-prod.properties: #生产环境

#activemq
spring.activemq.broker-url #指定 ActiveMQ broker 的 URL,默认自动生成. spring.activemq.in-memory #是否是内存模式,默认为 true. spring.activemq.password #指定 broker 的密码. spring.activemq.pooled #是否创建 PooledConnectionFactory ,而非
ConnectionFactory,默认 false
spring.activemq.user #指定 broker 的用户.

#aop
spring.aop.auto #是否支持@EnableAspectJAutoProxy,默认为: true
spring.aop.proxy-target-class #true 为使用 CGLIB 代理,false 为 JDK 代理,默认为 false

#application
spring.application.admin.enabled #是否启用 admin 特性,默认为: false
spring.application.admin.jmx-name #指定 admin MBean 的名称,默认为:
org.springframework.boot:type=Admin,name=SpringApplication

#artemis(HornetQ 捐献给 apache 后的版本)
spring.artemis.embedded.cluster-password #指定集群的密码,默认是启动时随机生成. spring.artemis.embedded.data-directory #指定 Journal 文件的目录.如果不开始持
久化则不必要指定. spring.artemis.embedded.enabled #是否开启内嵌模式,默认 true
spring.artemis.embedded.persistent #是否开启 persistent store,默认 false. spring.artemis.embedded.queues #指定启动时创建的队列,多个用逗号分隔,默认: []
spring.artemis.embedded.server-id #指定 Server ID. 默认是一个自增的数字,
从 0 开始. spring.artemis.embedded.topics #指定启动时创建的 topic,多个的话逗号分韩顺平 Java 工程师隔,默认: []
spring.artemis.host #指定 Artemis broker 的 host. 默认: localhost
spring.artemis.mode # 指 定 Artemis 的 部 署 模 式 , 默 认 为
auto-detected(也可以为 native or embedded). spring.artemis.port #指定 Artemis broker 的端口,默认为: 61616

#autoconfig
spring.autoconfigure.exclude #配置要排除的 Auto-configuration classes. #batch
spring.batch.initializer.enabled #是否在必要时创建 batch 表,默认为 true
spring.batch.job.enabled #是否在启动时开启 batch job,默认为 true
spring.batch.job.names #指定启动时要执行的 job 的名称,逗号分隔,默认所有 job 都会被执行
spring.batch.schema # 指 定 要 初 始 化 的 sql 语 句 路 径 , 默认:classpath:org/springframework/batch/core/schema-@@platform@@.sql)
spring.batch.table-prefix #指定批量处理的表的前缀.

#cookie、session 配置
server.session.cookie.comment #指定 session cookie 的 comment
server.session.cookie.domain #指定 session cookie 的 domain
server.session.cookie.http-only #是否开启 HttpOnly. server.session.cookie.max-age #设定 session cookie 的最大 age. server.session.cookie.name #设定 Session cookie 的名称. server.session.cookie.path #设定 session cookie 的路径. server.session.cookie.secure #设定 session cookie 的“Secure” flag. server.session.persistent #重启时是否持久化 session,默认 false
server.session.timeout #session 的超时时间
server.session.tracking-modes #设定 Session 的追踪模式(cookie, url, ssl).

#datasource
spring.dao.exceptiontranslation.enabled # 是 否 开 启
PersistenceExceptionTranslationPostProcessor,默认为 true
spring.datasource.abandon-when-percentage-full #设定超时被废弃的连接占到多少比例时要被关闭或上报
spring.datasource.allow-pool-suspension #使用 Hikari pool 时,是否允许连接池

..................................

b.resources\application.properties 修改配置:

  • 1.各 种 配 置 都 有 默 认 , 可 以 在 resources\application.properties 修 改 ,application.properties 文件我们可以手动创建
#默认 server.port=8080
server.port=10000
#比如: 默认 spring.servlet.multipart.max-file-size=1MB
#该属性可以指定 springboot 上传文件大小的限制
#默认配置最终都是映射到某个类上,比如这里配置会映射到 MultipartProperties
#把光标放在该属性,ctrl+b 就可以定位该配置映射到的类
spring.servlet.multipart.max-file-size=10MB

c.resources\application.properties 常用配置

#端口号
server.port=10000
#应用的上下文路径(项目路径)
server.servlet.context-path=/allModel

#指定 POJO 扫描包来让 mybatis 自动扫描到自定义的 POJO
mybatis.type-aliases-package=com.cxs.allmodel.model
#指定 mapper.xml 的路径
#(application 上配置了@MapperScan(扫面 mapper 类的路径)和 pom.xml 中放行了 mapper.xml 后,
# 配 置 mapper-locations 没 有 意 义 。 如 果 mapper 类 和 mapper.xml 不 在 同 一 个 路 径 下 时 ,
mapper-locations 就有用了)
mybatis.mapper-locations=classpath:com/cxs/allmodel/mapper
#session 失效时间(单位 s)
spring.session.timeout=18000
#数据库连接配置
#mysql 数据库 url
mysql.one.jdbc-url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=Asia/Shanghai&useSSL=false
#mysql 数据库用户名
mysql.one.username=
#数据库密码
mysql.one.password=
#线程池允许的最大连接数
mysql.one.maximum-pool-size=15
#日志打印:日志级别 trace<debug<info<warn<error<fatal 默认级别为 info,即默认打印 info 及其以
上级别的日志
#logging.level 设置日志级别,后面跟生效的区域,比如 root 表示整个项目,也可以设置为某个包下,
也可以具体到某个类名(日志级别的值不区分大小写)
logging.level.com.cxs.allmodel.=debug
logging.level.com.cxs.allmodel.mapper=debug
logging.level.org.springframework.web=info
logging.level.org.springframework.transaction=info
logging.level.org.apache.ibatis=info
logging.level.org.mybatis=info
logging.level.com.github.pagehelper = info
logging.level.root=info
#日志输出路径
logging.file=/tmp/api/allmodel.log
#配置 pagehelper 分页插件
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
#jackson 时间格式化
spring.jackson.serialization.fail-on-empty-beans=false
#指定日期格式,比如 yyyy-MM-dd HH:mm:ss,或者具体的格式化类的全限定名
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
#指定日期格式化时区,比如 America/Los_Angeles 或者 GMT+10
spring.jackson.time-zone=GMT+8
#设置统一字符集
spring.http.encoding.charset=utf8
#redis 连接配置
# redis 所在主机 ip 地址
spring.redis.host=
#redis 服务器密码
spring.redis.password=
#redis 服务器端口号
spring.redis.port=
#redis 数据库的索引编号(0 到 15)
spring.redis.database=14
## 连接池的最大活动连接数量,使用负值无限制
#spring.redis.pool.max-active=8
#
## 连接池的最大空闲连接数量,使用负值表示无限数量的空闲连接
#spring.redis.pool.max-idle=8
#
## 连接池最大阻塞等待时间,使用负值表示没有限制
#spring.redis.pool.max-wait=-1ms
#
## 最小空闲连接数量,使用正值才有效果
#spring.redis.pool.min-idle=0
#
## 是否启用 SSL 连接. ##spring.redis.ssl=false
#
## 连接超时,毫秒为单位
#spring.redis.timeout= 18000ms
#
## 集群模式下,集群最大转发的数量
#spring.redis.cluster.max-redirects=
#
## 集群模式下,逗号分隔的键值对(主机:端口)形式的服务器列表
#spring.redis.cluster.nodes=
#
## 哨兵模式下,Redis 主服务器地址
#spring.redis.sentinel.master=
#
## 哨兵模式下,逗号分隔的键值对(主机:端口)形式的服务器列表
#spring.redis.sentinel.nodes= 127.0.0.1:5050,127.0.0.1:5060

d.resources\application.properties 自定义配置

  • 1.还可以在 properties 文件中自定义配置,通过@Value("${}")获取对应属性值
application.properties 文件
my.website=https://www.baidu.com
  • 2.通过bean实例获取配置文件中的值:
//某个 Bean
@Value("${my.website}")
private String bdUrl;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值