首页 > 解决方案 > @Profile 在没有 Spring Boot 的情况下不起作用(-Dspring.profiles.active 与 maven)

问题描述

在没有 Spring Boot 的情况下,我无法@Profile使用 Maven 进行工作。在 pom.xml 中,我定义了 maven 配置文件(“env”和“dev”,这也是默认的)。

不幸的是,每当我尝试使用以下方式构建项目时:

mvn clean install -Dspring.profiles.active=env 

始终应用“默认”配置文件(在 Spring - maven 应用“env”用于 maven 目的)。我也试图让它与它一起工作System.getProperty("spring.profiles.active")System.getenv("spring.profiles.active")但那些总是返回 null。我认为还值得一提的是,这是非 Web 应用程序。

Beans(读取正确的属性):

    @Bean
    @Profile({"default"})
    public static PropertySourcesPlaceholderConfigurer defaultProperties() {
        return getPropertySourcesPlaceholderConfigurer("db.yml");
    }

    @Bean
    @Profile({"env"})
    public static PropertySourcesPlaceholderConfigurer envProperties() {
        return getPropertySourcesPlaceholderConfigurer("db-env.yml");
    }

    @Bean
    @Profile({"test"})
    public static PropertySourcesPlaceholderConfigurer devProperties() {
        return getPropertySourcesPlaceholderConfigurer("db-test.yml");
    }

    private static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer(String resource) {
        PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new ClassPathResource(resource));
        final Properties object = yaml.getObject();
        if (object != null) {
            propertySourcesPlaceholderConfigurer.setProperties(object);
        }
        return propertySourcesPlaceholderConfigurer;
    }

Pom.xml:

<profiles>
    <profile>
      <id>dev</id>
      <activation>
        <activeByDefault>true</activeByDefault>
        <property>
          <name>spring.profiles.active</name>
          <value>dev</value>
        </property>
      </activation>
    </profile>
    <profile>
      <id>env</id>
      <activation>
        <property>
          <name>spring.profiles.active</name>
          <value>env</value>
        </property>
      </activation>
    </profile>
  </profiles>

标签: javaspringmavenspring-profilesspring-properties

解决方案


Spring 配置文件用于运行您的应用程序,而不是构建。-Dspring.profiles.active=env执行应用程序时传递。在您的示例中,您正在执行mvn install不执行您的应用程序的操作。


推荐阅读