没有Spring Boot的@Profile不起作用(-Dspring.profiles.active with maven)

时间:2018-04-24 13:14:13

标签: java spring maven spring-profiles spring-properties

我无法让@Profile与maven一起工作而没有Spring Boot。 在pom.xml中我定义了maven配置文件(“env”和“dev”也是默认值)。

每当我尝试使用以下内容构建项目时都会不幸:

mvn clean install -Dspring.profiles.active=env 

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

豆(阅读适当的属性):

    @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>

2 个答案:

答案 0 :(得分:1)

运行命令时需要指定Maven配置文件(而不是Spring配置文件):

mvn clean install -Penv

请参阅:http://maven.apache.org/guides/introduction/introduction-to-profiles.html

答案 1 :(得分:1)

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