简体   繁体   中英

auto-configuration adding PropertySource in spring-boot

I want to add a custom PropertySource (the class, not annotation). Annotation is not sufficient as it only handles file sources.

The approach which works is to define own ApplicationContextInitializer and add proper declaration to META-INF/spring.factories. ApplicationContextInitializer just uses: Environment.getPropertySources().addLast(...) But there are some drawbacks, mainly:

  • It is always run, but the preferable behaviour would be to only run if certain conditions are met (@ConditionalOnClass, etc)

How to achieve that? Ideally I'd write my autoconfiguration with @Condition... annotations and inside declare such initializer (preferably Ordered).

Edit: In my particular case I want to define Archaius PolledConfigurationSource, but only if Archaius is on the classpath - that's why I'd like to use @ConditionalOnClass together with a listener on an event very early in the lifecycle.

You could have an intermediary class - part of your application, let's call it the "ProviderConfigurer" - of which goal will be to load a Service (packaged in a separate jar with META-INF/services/targetSPi) that in turn will load Archaius. So to activate Archaius you will have to place 2 jars instead of one, but then the ProviderConfigurer will be able to load the property source provided by the Service (the API will be part of the interface you will have to define...) if any is discovered in the class path and do nothing in case the Service doesn't find any class implementing the SPI you will define for the purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM