Spring外部化配置的幾種技巧分享
@Log4j2@SpringBootApplicationpublic class ConfigurationApplication { public static void main(String[] args) {SpringApplication.run(ConfigurationApplication.class, args); } @Bean ApplicationRunner applicationRunner(Environment environment){return args -> { log.info('user.name : {}',environment.getProperty('user.name'));}; }}修改Spring默認(rèn)配置文件名稱
啟動(dòng)程序參數(shù)中加入如下配置:
--spring.config.name=appValue注解配置來(lái)源
配置文件
@BeanApplicationRunner applicationRunner(Environment environment, @Value('${greeting.message:hello boy}') String message){ return args -> { log.info('from application.properties user.name : {}',environment.getProperty('user.name')); log.info('from application.properties greeting.message : {}',message); };}
默認(rèn)值
value注解通過(guò)冒號(hào)來(lái)配置默認(rèn)值:
@Value('${greeting.message:hello boy}')
獲取環(huán)境變量值
獲取程序參數(shù)值
外部化配置文件優(yōu)先級(jí)問(wèn)題如果有application.properties在springboot 啟動(dòng)jar包同一目錄,會(huì)優(yōu)先讀取這個(gè)文件中的配置。
Autowire注入ConfigurableEnvrionmentpublic static void main(String[] args) {new SpringApplicationBuilder().sources(ConfigurationApplication.class).run(args);}@Autowiredvoid getConfigurableEnvrionment(ConfigurableEnvironment environment) { environment.getPropertySources().addLast(new MyPropertySource());}ApplicationInitialiazer 配置
public static void main(String[] args) {new SpringApplicationBuilder().sources(ConfigurationApplication.class).initializers(applicationContext -> applicationContext.getEnvironment().getPropertySources().addLast(new MyPropertySource())).run(args); }static class MyPropertySource extends PropertySource<String>{ public MyPropertySource() { super('myproperty'); } @Override public Object getProperty(String name) { if(name.equalsIgnoreCase('author-name')){ return 'john'; } return null; }}
然后通過(guò)@Value注解注入獲取author-name:
@Bean ApplicationRunner applicationRunner(Environment environment,@Value('${greeting.message:hello boy}') String message,@Value('${author-name}') String name){return args -> { log.info('from application.properties user.name : {}',environment.getProperty('user.name')); log.info('from application.properties author.name : {}',name);}; }總結(jié)
Spring的Environment抽象有很多值得學(xué)習(xí)的地方,期待下一期每日小技巧。
以上就是Spring外部化配置的幾種技巧分享的詳細(xì)內(nèi)容,更多關(guān)于Spring外部化配置的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. JavaScript Tab菜單實(shí)現(xiàn)過(guò)程解析2. python opencv 實(shí)現(xiàn)讀取、顯示、寫(xiě)入圖像的方法3. javascript設(shè)計(jì)模式 ? 建造者模式原理與應(yīng)用實(shí)例分析4. jsp+mysql實(shí)現(xiàn)網(wǎng)頁(yè)的分頁(yè)查詢5. ASP.NET MVC通過(guò)勾選checkbox更改select的內(nèi)容6. javascript xml xsl取值及數(shù)據(jù)修改第1/2頁(yè)7. 使用AJAX(包含正則表達(dá)式)驗(yàn)證用戶登錄的步驟8. Android實(shí)現(xiàn)圖片自動(dòng)切換功能(實(shí)例代碼詳解)9. Python使用oslo.vmware管理ESXI虛擬機(jī)的示例參考10. 存儲(chǔ)于xml中需要的HTML轉(zhuǎn)義代碼
