YML文件

文章讨论了在SpringBoot项目中如何正确读取YML配置文件,包括application.yml加载其他yml文件,使用@ConfigurationProperties注解绑定配置属性。在测试案例中,展示了bookorder对象的初始化,但测试结果显示time字段为null,可能存在配置解析问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

yml key 和value 之間必須有一個空格

SpringBoot通過
@Value(“${upload.path}”) 或者
@ConfigurationProperties(prefix = “upload”)
讀取不到value

upload:
path:X d:/upload

application.yml加载其它yml文件

spring:
  profiles:
    include: 'order'

定义application-order.yml

bookorder:
  orderID: ${random.int}
  orderName: "TSL order bill"
  des: "a good car"
  time:
    type: DateTime<'Y-m-d H:i:s'>
    groups: [detailed]
  buyer:
    - id: 1
      name: Claire
    - id: 2
      name: Jeff   

@component && @ConfigurationProperties(prefix=“bookorder”)

@Data
@Component
@Slf4j 
@Builder
@AllArgsConstructor
@NoArgsConstructor
@JsonPropertyOrder(value= {"time","orderName"})
@ConfigurationProperties(prefix="bookorder")
public class Order {
	//@JsonIgnore
	public long orderID;
	public String orderName;
	public String des;
	@JsonFormat(shape = JsonFormat.Shape.STRING, 
	pattern = "yyyy-MM-dd hh:mm:ss", timezone = "GMT+8")
	public Date time;
	//@JsonProperty("buy")
	//@JsonInclude(JsonInclude.Include.NON_NULL)
	public List<Buyer> buyer;
}

测试Case

@SpringBootTest
@Slf4j
class OrderInitiationTest {

	@Resource
	Order order;
	
	@Test
	void test() {
		log.info(order.toString());
	}

}

测试结果

Order(orderID=-1804440514, orderName=TSL order bill, 
des=a good car, time=null, 
buyer=[Buyer(id=1, name=Claire), Buyer(id=2, name=Jeff)])
### 如何运行 YML 文件 YML 文件本身是一种数据序列化格式,主要用于存储配置信息。它并不能像脚本一样直接执行,而是通过其他编程语言加载并解析其内容来实现功能。 #### 加载和解析 YML 文件的方式 要运行 YML 文件的内容,通常需要借助支持 YAML 的库将其转换为程序中的对象结构。以下是 Python 中的一个典型例子: ```python import yaml try: with open("example.yml", "r") as file: data = yaml.safe_load(file) print(data) except Exception as e: print(f"Error loading YAML file: {e}") ``` 上述代码展示了如何使用 `PyYAML` 库读取名为 `example.yml` 的文件,并将其内容安全地加载到变量 `data` 中[^2]。 #### 运行环境的要求 为了成功运行 YML 配置文件,需满足以下条件: 1. **安装必要的依赖**:如果使用的是 Python,则需要先安装 PyYAML 或类似的库。可以通过 pip 安装该库: ```bash pip install pyyaml ``` 2. **确保语法正确**:YML 文件对缩进有严格要求,错误的缩进可能导致解析失败。例如,下面是一个简单的有效 YML 结构[^5]: ```yaml spring: config: import: classpath:additional-config.yml ``` 3. **处理特殊字符**:当 URL 或字符串中包含特殊字符时,应适当转义或使用引号包裹。例如,在数据库连接字符串中可能遇到的情况如下所示[^4]: ```yaml url: "jdbc:mysql://111.11.1.1:3306/qzxl_iot?useUnicode=true&xxx&useSSL=false" ``` #### 多文档的支持 YML 支持在同一文件内定义多个独立的文档,这些文档由 `---` 分隔符分开。这种特性对于批量传输配置或者分割逻辑单元很有帮助。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值