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默認配置文件名稱
啟動程序參數中加入如下配置:
--spring.config.name=appValue注解配置來源
配置文件
@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); };}
默認值
value注解通過冒號來配置默認值:
@Value('${greeting.message:hello boy}')
獲取環境變量值
獲取程序參數值
外部化配置文件優先級問題如果有application.properties在springboot 啟動jar包同一目錄,會優先讀取這個文件中的配置。
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; }}
然后通過@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);}; }總結
Spring的Environment抽象有很多值得學習的地方,期待下一期每日小技巧。
以上就是Spring外部化配置的幾種技巧分享的詳細內容,更多關于Spring外部化配置的資料請關注好吧啦網其它相關文章!
相關文章: