You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Micronaut 4.1.3使用@PropertySource加载自定义YAML文件报错求解决方案

解决Micronaut 4.1.3中@PropertySource加载自定义YAML文件的类型不兼容问题

错误原因

Micronaut 4.x版本对@PropertySource注解的参数做了调整,默认参数类型为io.micronaut.context.annotation.Property[],不再支持直接传入资源路径字符串,这就是触发类型不兼容错误的原因。

解决办法

使用@PropertySource的resources属性指定自定义YAML文件路径,再结合属性绑定注解将配置值注入到类字段中,以下是两种常见实现方式:

方式一:结合@ConfigurationProperties(推荐批量绑定)

import io.micronaut.context.annotation.ConfigurationProperties;
import io.micronaut.context.annotation.PropertySource;

@PropertySource(resources = "classpath:new.yaml")
@ConfigurationProperties("test") // 对应yaml文件中的属性前缀
public class TestConfig {
    private String first;

    // 必须提供Getter和Setter,Micronaut通过反射绑定属性
    public String getFirst() {
        return first;
    }

    public void setFirst(String first) {
        this.first = first;
    }
}

对应的new.yaml内容示例:

test:
  first: "自定义配置值"

方式二:结合@Value(适合单个属性注入)

import io.micronaut.context.annotation.PropertySource;
import jakarta.inject.Singleton;
import io.micronaut.core.value.annotation.Value;

@Singleton
@PropertySource(resources = "classpath:new.yaml")
public class TestConfig {
    @Value("${first}") // 直接引用yaml中的属性键
    private String first;

    public String getFirst() {
        return first;
    }
}

对应的new.yaml内容示例:

first: "自定义配置值"

注意事项

  • 确保new.yaml文件放置在src/main/resources目录下,保证编译后能被类路径加载到
  • YAML文件格式要规范,避免缩进或语法错误导致配置无法解析

内容的提问来源于stack exchange,提问作者Third Fon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 14:43:22