【问题标题】:Could not resolve placeholder spring.profiles.active but at the same time profiles are active无法解析占位符 spring.profiles.active 但同时配置文件处于活动状态
【发布时间】:2023-02-24 05:12:46
【问题描述】:

我有一个 Spring 引导控制台应用程序,它使用命令行中指定的多个活动配置文件启动。 简化的代码如下所示:

package tmp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;

@SpringBootApplication(scanBasePackages = {"tmp"})
@Configuration
public class SampleTool implements CommandLineRunner {

    @Autowired
    private Environment environment;

    @Value("${spring.profiles.active[0]}")
    private String firstProfile;

    // Dummy data source just for the sake of starting JPA 
    @Bean
    public DataSource getDataSource() throws ClassNotFoundException{
        DataSourceBuilder dsBuilder = DataSourceBuilder.create();
        dsBuilder.driverClassName("com.mysql.jdbc.Driver");
        dsBuilder.url("jdbc:mysql://localhost/test");
        dsBuilder.username("...");
        dsBuilder.password("...");
        return dsBuilder.build();
    }
    public void run(String...args) {
        System.exit(0);
    }
    public static void main(String[] args) {
        SpringApplication.run(SampleTool.class, args);
    }
}

奇怪的是,在执行时,我看到以下内容:

2023-02-23 08:34:44.696  INFO 38840 --- [           main] tmp.SampleTool   : The following 2 profiles are active: "local-db", "local-wiki"

但是应用程序崩溃了

Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.profiles.active[0]' in value "${spring.profiles.active[0]}"

为什么 Spring 不注入活动配置文件(如果存在)?

【问题讨论】:

    标签: spring-boot spring-profiles


    【解决方案1】:

    您可以按如下方式注入第一个配置文件:

    @Value("#{'${spring.profiles.active:}'.split(',')[0]}")
    private String firstProfile;
    

    由于 spring.profiles.active 包含以逗号分隔的配置文件名称,因此在访问第一个元素之前应以逗号分隔。 : 用于定义默认值,以防止在没有配置文件处于活动状态时出现 java.lang.IllegalArgumentException: Could not resolve placeholder 异常。

    供参考:Spring Profiles

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-27
      • 2013-10-03
      • 2023-03-26
      • 2010-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-05
      相关资源
      最近更新 更多