Spring Boot Profile не выбирает файлы свойств - PullRequest
0 голосов
/ 11 октября 2019

Мы работаем над Spring Boot 2.1.6, и нам нужно реализовать профиль весенней загрузки в нашем приложении

В настоящее время в нашем проекте есть два файла свойств application.properties и bucket.properties (конфигурация s3).

поэтому мы создали два файла свойств ресурсов resources / application-dev.properties и файл resources / bucket-dev.properties для среды Dev.

Передаем аргументы виртуальной машины в следующем примере. Программа -Dspring.profiles.active = dev, чтобы правильно подобрать файлы.

Мы используем конфигурацию на основе XML и, следовательно, загружаем файл свойств, используя приведенное ниже определение.

<bean id="applicationProperties"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
        <property name="locations" >
            <list>
                <value>classpath:application-${spring.profiles.active:dev}.properties</value>
                <value>classpath:bucket-${spring.profiles.active:dev}.properties</value>
            </list>
        </property>
</bean>

Вышеуказанная конфигурация работает нормально, и при загрузке с пружиной можно правильно подобрать файлы.

Но я хочу создать нижеуказанную структуру папок в папке ресурсов для правильного разделения файлов.

|
resources
        |dev
            |
            application-dev.properties  
            bucket-dev.properties

Как только я это сделаю, я внес изменения в вышеуказанный PropertyPlaceholderConfigurer, как показано ниже.

<bean id="applicationProperties"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
        <property name="locations" >
            <list>
                <value>classpath:${spring.profiles.active}/application-${spring.profiles.active:dev}.properties</value>
                <value>classpath:${spring.profiles.active}/bucket-${spring.profiles.active:dev}.properties</value>
            </list>
        </property>
</bean>

Как только я запускаю приложение, используя вышеуказанную конфигурацию, он не может найти свойства, определенные внутри вышеуказанного файла, и не запускает приложение.

Пожалуйста, дайте мне знать, чтоМне не хватает вышеуказанной конфигурации.

Примечание. Мы не используем конфигурацию на основе аннотаций в Spring Boot App, а используем только конфигурацию на основе XML.

1 Ответ

2 голосов
/ 11 октября 2019

Springboot не будет делать это из коробки, но вы можете использовать PropertySourcesPlaceholderConfigurer для этого.

@Configuration
public class PropertyFileLoaderConfig {

    private static final Logger LOG = LoggerFactory.getLogger(PropertyFileLoaderConfig.class);

    private static final String PROFILE_DEV = "dev";
    private static final String PROFILE_STAGE = "stage";
    private static final String PROFILE_PROD = "prod";

    private static final String PATH_TEMPLATE = "classpath*:%s/*.properties";

    @Bean
    @Profile(PROFILE_DEV)
    public static PropertySourcesPlaceholderConfigurer devPropertyPlaceholderConfigurer() throws IOException {
        LOG.info("Initializing {} properties.", PROFILE_DEV);
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        configurer.setLocations(new PathMatchingResourcePatternResolver().getResources(getResourcesFromPath(PROFILE_DEV)));//Loads all properties files from the path
        configurer.setIgnoreUnresolvablePlaceholders(true);

        return configurer;
    }

    @Bean
    @Profile(PROFILE_STAGE)
    public static PropertySourcesPlaceholderConfigurer stagePropertyPlaceholderConfigurer() throws IOException {
        LOG.info("Initializing {} properties.", PROFILE_STAGE);
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        configurer.setLocations(new PathMatchingResourcePatternResolver().getResources(getResourcesFromPath(PROFILE_STAGE)));

        return configurer;
    }

    @Bean
    @Profile(PROFILE_PROD )
    public static PropertySourcesPlaceholderConfigurer prodPropertyPlaceholderConfigurer() throws IOException {
        LOG.info("Initializing {} properties.", PROFILE_PROD );
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        configurer.setLocations(new PathMatchingResourcePatternResolver().getResources(getResourcesFromPath(PROFILE_PROD )));

        return configurer;
    }

    private static String getResourcesFromPath(String path) {
        return PATH_TEMPLATE.replaceFirst("%s", path);
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...