Spring Boot匯入多個外部配置檔(properties files)的設定方式如下。
例如下面是Spring的配置類別DemoConfiguration
,共匯入message.properties
,error.properties
,db.properties
三個properties files。
原本@PropertySource
的value
即可設定多個路徑來匯入多個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 {
}
參考:
沒有留言:
張貼留言