項目開發中,手動去讀取Properties,太過於麻煩,而且使用不方便。
Spring Boot 自帶Properties文件讀取。
Properties文件java
masterDb.maxConnectionsPerHost=100 masterDb.connectTimeOut=60000 masterDb.threadsAllowedToBlockForConnectionMultiplier=50 masterDb.maxWaitTime=60000 masterDb.host=mongodbhost masterDb.port=27017 masterDb.user=appHost masterDb.pwd=abc123_ masterDb.authDb=admin
對應的java Beanspring
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; @Component // 前綴 @ConfigurationProperties(prefix = "masterDb") // 文件路徑,可使用${}表達式獲取spring environment屬性 @PropertySource("classpath:masterDb.properties") public class MasterDbProperties { private int maxConnectionsPerHost; private int threadsAllowedToBlockForConnectionMultiplier; private int maxWaitTime; private int connectTimeout; // getters and setters.... }
主類mongodb
@SpringBootApplication // 不能使用 @EnableConfigurationProperties(MasterDbProperties.class) // 會致使bean被初始化兩次 @EnableConfigurationProperties public class CoreApp { public static void main(String [] args) { SpringApplication.run(CoreApp.class, args); } }