首页 > 解决方案 > 加载活动属性文件 spring boot

问题描述

我想从活动配置文件中读取值,或者可以说活动属性文件。我有三个属性文件

我已将活动配置文件设置dev为如下

spring.profiles.active=dev

我的application-dev.properties文件有一个我想在课堂上阅读的条目。

应用程序-dev.properties 文件

fix.connection.type=initiator

我尝试阅读此条目

@Configuration
@PropertySource("classpath:application-${spring.profiles.active}.properties")
@Component
public class AdaptorDestination {
    @Value("${fix.connection.type}")
    private String connectionType;
}

例外

nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.profiles.active' in value "classpath:application-${spring.profiles.active}.properties"

请帮帮我

标签: spring-boot

解决方案


您无需使用@PropertySource注释即可使用注释加载属性@Value。Spring 将@Value自动从当前活动配置文件加载属性。

此外,您不需要${spring.profiles.active}@PropertySource注释中指定,因为默认情况下 Spring 总是从当前活动的配置文件中加载属性。Spring 根据配置文件后缀自动解析文件名。

所以您只需要指定基本文件名,例如: @PropertySource("classpath:application.properties") 如果当前活动的配置文件是“dev”,Spring 将首先从application.properties文件加载属性,然后用文件中的属性覆盖它们application-dev.properties

你可以在这里阅读更多


推荐阅读