@Profile не работает без Spring Boot (-Dspring.profiles.active с maven) - PullRequest
0 голосов
/ 24 апреля 2018

У меня проблемы с тем, чтобы @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 ]

0 голосов
/ 24 апреля 2018

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

0 голосов
/ 24 апреля 2018

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

mvn clean install -Penv

См .: http://maven.apache.org/guides/introduction/introduction-to-profiles.html

...