@Profile не работает без Spring Boot (-Dspring.profiles.active с maven)

У меня проблемы с тем, чтобы сделать @Profile работать с Maven и без Spring Boot. В 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") но те всегда возвращали ноль. Я думаю также стоит упомянуть, что это не веб-приложение.

Бобы (чтобы прочитать правильные свойства):

    @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 ответа

Решение

Профили Spring предназначены для запуска вашего приложения, а не для сборки. Пройти -Dspring.profiles.active=env когда вы выполняете свое заявление. В вашем примере вы делаете mvn install который не выполняет ваше приложение.

Вам нужно указать профиль Maven (не профиль Spring) при запуске команды:

mvn clean install -Penv

Смотрите: http://maven.apache.org/guides/introduction/introduction-to-profiles.html

Другие вопросы по тегам