yaml配置
发布日期:2021-06-30 22:58:38 浏览次数:2 分类:技术文章

本文共 2812 字,大约阅读时间需要 9 分钟。

yaml配置和properties配置的区别:

1.yaml配置是有序的,properties配置是无序的

2.自定义的yaml目前不支持使用注解直接注入到SpringBoot项目中

依赖

在这里插入图片描述

 我们可以发现Spring-web中本身就包含yaml相关的包
在这里插入图片描述

一、yaml注入数组

1.新建并配置application.yml文件

server:  port: 8081  servlet:    context-path: /alvin## 配置不同服务器Redis集群redis:  port: 6379  hosts:    - 121.40.80.81    - 121.40.80.82    - 121.40.80.83    - 121.40.80.84

2.创建实体类RedisCluster.java

//将此类注入Spring容器@Component//引入Redid相关配置@ConfigurationProperties("redis")public class RedisCluster {
private Integer port; private List
hosts; @Override public String toString() {
return "RedisCluster{" + "port=" + port + ", hosts=" + hosts + '}'; } public Integer getPort() {
return port; } public void setPort(Integer port) {
this.port = port; } public List
getHosts() {
return hosts; } public void setHosts(List
hosts) {
this.hosts = hosts; }}

3.进行单元测试

在这里插入图片描述

在这里插入图片描述

二、yaml注入对象

1.配置application.yml

server:  port: 8081  servlet:    context-path: /alvinredis:  port: 6379  hosts:    - 121.40.80.81    - 121.40.80.82    - 121.40.80.83    - 121.40.80.84  redisList:    - port: 6379      host: 121.40.80.90    - port: 6380      host: 121.40.80.91

2.修改实体类RedisCluster,创建Redis实体类

  • RedisCluster
@Component@ConfigurationProperties("redis")public class RedisCluster {
private Integer port; private List
hosts; //引入对象 private List
redisList; @Override public String toString() {
return "RedisCluster{" + "port=" + port + ", hosts=" + hosts + ", redisList=" + redisList + '}'; } public List
getRedisList() {
return redisList; } public void setRedisList(List
redisList) {
this.redisList = redisList; } public Integer getPort() {
return port; } public void setPort(Integer port) {
this.port = port; } public List
getHosts() {
return hosts; } public void setHosts(List
hosts) { this.hosts = hosts; }}
  • Redis
public class Redis {
private Integer port; private String host; @Override public String toString() {
return "Redis{" + "port=" + port + ", host='" + host + '\'' + '}'; } public Integer getPort() {
return port; } public void setPort(Integer port) {
this.port = port; } public String getHost() {
return host; } public void setHost(String host) {
this.host = host; }}

3.进行单元测试

在这里插入图片描述

三、profile实现分工配置

propertiesyaml是一样的 只是文件扩展名不同

在这里插入图片描述

启动方式:

在需要启动的配置环境下,写激活配置:

spring.profiles.active=dev

转载地址:https://lukeyalvin.blog.csdn.net/article/details/104099618 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:让你的Windows变成一台Mac
下一篇:Spring属性注入

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2024年04月25日 11时37分35秒