AdSense

網頁

2019/11/9

Spring Boot 設定多個外部配置檔 multiple properties files configuration

Spring Boot匯入多個外部配置檔(properties files)的設定方式如下。


例如下面是Spring的配置類別DemoConfiguration,共匯入message.propertieserror.propertiesdb.properties三個properties files。


原本@PropertySourcevalue即可設定多個路徑來匯入多個properties檔,例如

DemoConfiguration

package com.abc.demo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@PropertySource(
        value = {"classpath:message.properties",
                "classpath:error.properties",
                "classpath:db.properties"},
        ignoreResourceNotFound = true
)
@Configuration
public class DemoConfiguration {
}

在Java 8開始支援可定義重覆的annotation(Repeating Annotations),所以可改成下面。

DemoConfiguration

package com.abc.demo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@PropertySource("classpath:message.properties")
@PropertySource("classpath:error.properties")
@PropertySource(value = "classpath:db.properties", ignoreResourceNotFound = true)
@Configuration
public class DemoConfiguration {
}


或使用Spring 4才有的@PropertySources來匯入多個properties檔的設定。

DemoConfiguration

package com.abc.demo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;

@PropertySources({
    @PropertySource("classpath:message.properties"),
    @PropertySource("classpath:error.properties"),
    @PropertySource(value = "classpath:db.properties", ignoreResourceNotFound = true)
})
@Configuration
public class DemoConfiguration {
}


參考:

沒有留言:

AdSense