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