在spring boot種自訂設定檔的讀取很方便, 不用在寫propert的讀取類來讀取設定檔信息。
下面是我試過的讀取springboot讀取設定檔的幾種方法:
準備:
1.在application.yml檔種加入配置資訊:
hank: testConfig: TestDriver2.新建立設定檔 dbConfig.properties
jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/testjdbc.username=rootjdbc.password=rootorg.hank.testconfig = testConfig前面的準備 中我們知道
hank.testConfig 是在application.yml文件中, 此文件為springboot的默認設定檔jdbc.driver 是在我們自訂的設定檔中的key方法一:用springboot 自帶的類Environment
測試:
@Autowiredprivate Environment env;@Testpublic void testConfigDefault { logger.info("Environment get default properties:" + env.getProperty("hank.testConfig")); logger.info("Environment get self properties:" + env.getProperty("jdbc.driver"));}測試結果
Environment get default properties:TestDriver
Environment get self properties:null
結論:也就是說Environment自帶的只能讀取預設的設定檔裡面的配置資訊, 自訂的設定檔在Environment是讀取不了的。 況且在application.yml配置的都是系統自身的項, 也就是不隨系統環境改變而改變的配置項。 一些易變的配置項我們還是自訂檔的比較好。
方法二:Configurable
建立類ConfigDefault 注解@Configurable
@Component@Configurablepublic class ConfigDefault { @Value("${hank.testConfig}") private String hankConfig; @Value("${org.hank.testconfig}") private String selfConfig; getter and setter....}測試:
@Autowiredprivate ConfigDefault configDefault;@Testpublic void testConfigDefault { logger.info("defualt config--hank.testConfig:" + configDefault.getHankConfig); logger.info("self config--org.hank.testconfig:" + configDefault.getSelfConfig);}測試結果:直接報錯, Could not resolve placeholder 'org.hank.testconfig' in value "${org.hank.testconfig}"
也就說application.yml檔中沒有org.hank.testconfig這配置項, 所以在類上加@Configurable也是默認唯讀取application.yml檔的配置項
方法三:@PropertySource注解
新建model類:
@Component@PropertySource("classpath:dbConfig.properties")public class DataBaseConfig { @Value("${jdbc.driver}") private String driver; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String userName; @Value("${jdbc.password}") private String password; @Value("${hank.testConfig}") //測試默認設定檔 private String hankConfig; getter and setter...}測試:
@Autowiredprivate DataBaseConfig config;@Testpublic void testGetDataBaseConfig { logger.info("self Config Driver:" + config.getDriver); logger.info("default config hank.testConfig:" + config.getHankConfig);}測試結果:
self Config Driver:com.mysql.jdbc.Driver
default config hank.testConfig:TestDriver
可以看出連同預設配置的資訊也讀取到了
結論:用@PropertySource("classpath:dbConfig.properties")
指定自訂設定檔路徑就可以讀取到自訂的設定檔資訊, 而對於預設設定檔application.yml我們也能在讀取自訂設定檔的同時讀取到預設設定檔的資訊。
以上就是三中讀取設定檔的方式, 可以看到要想讀取自訂的設定檔, 就必須要注解指定設定檔路徑。