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

Spring Boot如何通过@Value读取依赖Jar包内的application.yml配置

解决方案

Spring Boot默认只会加载优先级最高的同命名配置文件,若依赖Jar包和主项目的配置文件都命名为application.yml,依赖Jar内的配置会被主项目的同名配置覆盖,因此无法直接读取,可通过以下方案解决:

方案1:修改依赖Jar配置文件名避免冲突(兼容性最好)

  • 将依赖Jar包内的配置文件重命名为不会和主项目冲突的名称,比如dependency-config.yml
  • 在依赖Jar的配置类上添加@PropertySource注解指定加载该配置,yaml格式需要额外指定解析工厂类:
@Configuration
@PropertySource(value = "classpath:dependency-config.yml", factory = YamlPropertySourceFactory.class)
public class DependencyAutoConfig {
    // 此处可正常用@Value读取对应配置
    @Value("${dependency.config.key}")
    private String configKey;
}
  • 配套的Yaml解析工厂实现代码如下:
public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        Properties properties = factory.getObject();
        return new PropertiesPropertySource(Objects.requireNonNull(resource.getResource().getFilename()), properties);
    }
}

方案2:通过spring.config.import引入(Spring Boot 2.4+版本支持)

无需修改依赖Jar代码,直接在主项目的application.yml中添加导入配置即可:

spring:
  config:
    import: classpath:application.yml # 此处填写依赖Jar中配置文件的路径

注意:同名配置后导入的会覆盖之前加载的配置,需根据需求调整导入顺序,避免主项目的配置被依赖Jar的配置覆盖。

方案3:使用@ConfigurationProperties绑定

如果依赖Jar的配置为统一前缀,可使用配置绑定实现更优雅的读取:

  • 在依赖Jar中添加配置绑定类:
@ConfigurationProperties(prefix = "dependency.custom")
public class DependencyProperties {
    private String key1;
    private Integer key2;
    // 省略getter、setter方法
}
  • 要么在依赖Jar的自动配置类上添加@EnableConfigurationProperties(DependencyProperties.class),要么在主项目启动类上添加@ConfigurationPropertiesScan(basePackages = "依赖Jar配置类所在包路径"),后续直接注入DependencyProperties类即可读取所有配置。

内容的提问来源于stack exchange,提问作者Shambhavi Rai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:06:05