Spring 启动找不到配置文件特定的属性文件

Spring Boot can't find profile-specific properties files

我正在关注 Spring documentation 为我的 SpringBoot 应用程序使用特定于配置文件的 属性 文件。我在 src/main/resources 下有 2 个 属性 文件:datasource.properties 用于本地开发,datasource-prod.properties 用于服务器数据源配置。

这是我的 DataSourceConfiguration.java 配置 class :

@Configuration
@PropertySource("classpath:datasource-{profile}.properties")
@Slf4j
public class DataSourceConfiguration {

    @Value("${flad.datasource.driver}")
    private String dataSourceDriverClassName;
    @Value("${flad.datasource.url}")
    private String dataSourceUrl;
    @Value("${flad.datasource.username}")
    private String dataSourceUsername;
    @Value("${flad.datasource.password}")
    private String dataSourcePassword;

    @Bean
    public DataSource getDataBase(){
        log.info("Datasource URL = {}", dataSourceUrl);
        return DataSourceBuilder
                .create()
                .driverClassName(dataSourceDriverClassName)
                .url(dataSourceUrl)
                .username(dataSourceUsername)
                .password(dataSourcePassword)
                .build();
    }
}

当我启动我的 SpringBootApplication main class 时,无论我是否使用 -Dspring.profiles.active=prod 我都会收到以下错误:

17:05:49.008 [restartedMain] ERROR org.springframework.boot.SpringApplication - Application run failed
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [fr.payet.flad.core.config.CoreConfig]; nested exception is java.io.FileNotFoundException: class path resource [datasource-{profile}.properties] cannot be opened because it does not exist

我找到的解决方案是重命名我的 属性 文件 datasource-local.propertiesdatasource-prod.properties,以这种方式使用 @PropertySource @PropertySource("classpath:datasource-${profile}.properties") 当我启动我的 SpringBoot 应用程序时,我使用 -Dprofile=local 作为 VM 选项