application.yml配置文件拆分方式
尽管使用springboot减少了很多配置,但还是有一些配置需要大量的手工操作,而yml格式的配置文件在配置较少时,比较直观,但是在配置较多时,就不是很好了,因此拆分配置文件就很有必要了,拆分配置文件也比较简单。
# application.yml 文件 spring: profiles: include: - sharding - kanyun
主配置文件中 通过 spring.profiles.include来引入其他配置文件
# application-sharding.yml spring: shardingsphere: datasource: names: dms dms: type: com.zaxxer.hikari.hikaridatasource jdbc-url: jdbc:mysql://localhost:3306/rds_mysql_1352zk username: root password: root sharding: tables: t_user: actual-data-nodes: dms.t_user_$->{1..2} table-strategy: inline: sharding-column: id algorithm-expression: t_user_$->{id % 2 + 1} key-generator: column: id type: simple enabled: true props: sql: show: true
# application-kanyun.properties banner.location=banner.txt #可以自定义输出信息的位置 banner.charset=utf-8 #指定编码格式 spring.main.banner-mode=console
这里需要注意的是,如果在主配置文件application.yml中include了错误的文件名,也不会报找不到文件的错,除非关键配置信息找不到会报错。
需要注意的是,include不但可以引入yml文件,还可以引入properties文件,配置也是生效的。
这样就可以自定义配置文件的格式,毕竟有些配置用properties文件更方便一些。
application.yml配置文件写法
一、存放位置分类
- 1.当前项目根目录下的config目录下
- 2.当前项目的根目录下
- 3.resources目录下的config目录下
- 4.resources目录下
按照这上面的顺序,4个配置文件的优先级依次降低。
二、自定义存放位置和自定义命名
自定义存放位置和自定义配置文件命令和application.properties配置类型
请参考一下springboot配置文件application.properties的理解
三、yml属性特殊注入
yml注册数组注入,例如
company: urls: - https://www.aa.com - https://www.bb.com
这些数据可以绑定到一个bean类中
import org.springframework.boot.context.properties.configurationproperties; import org.springframework.stereotype.component; import java.util.arraylist; import java.util.list; /** * @author qinxun * @date 2023-06-15 * @descripion: 测试 */ @component @configurationproperties(prefix = "company") public class website { private list<string> urls = new arraylist<>(); public list<string> geturls() { return this.urls; } }
测试
import com.example.springbootdemo.bean.website; import org.junit.jupiter.api.test; import org.springframework.beans.factory.annotation.autowired; import org.springframework.boot.test.context.springboottest; @springboottest class springbootdemoapplicationtests { @autowired private website website; @test void contextloads() { // 输出 [https://www.aa.com, https://www.bb.com] system.out.println(website.geturls()); } }
四、和application.properties的区别
1.properties文件是无序的,yml文件是有序的。
2.yml配置不支持@propertysource注解
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论