简体   繁体   English

自动配置在Spring-boot中添加PropertySource

[英]auto-configuration adding PropertySource in spring-boot

I want to add a custom PropertySource (the class, not annotation). 我想添加一个自定义PropertySource(该类,而不是注释)。 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并将适当的声明添加到META-INF / spring.factories。 ApplicationContextInitializer just uses: Environment.getPropertySources().addLast(...) But there are some drawbacks, mainly: ApplicationContextInitializer仅使用: Environment.getPropertySources().addLast(...)但有一些缺点,主要是:

  • It is always run, but the preferable behaviour would be to only run if certain conditions are met (@ConditionalOnClass, etc) 它始终运行,但是最好的行为是仅在满足某些条件时运行(@ConditionalOnClass等)

How to achieve that? 如何实现呢? Ideally I'd write my autoconfiguration with @Condition... annotations and inside declare such initializer (preferably Ordered). 理想情况下,我将使用@Condition ...批注编写自动配置,并在内部声明此类初始化程序(最好是有序的)。

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. 编辑:在我的特定情况下,我想定义Archaius PolledConfigurationSource,但仅当Archaius在类路径上时-这就是为什么我想在生命周期的早期就将@ConditionalOnClass与事件的侦听器一起使用。

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. 您可能有一个中间类-您的应用程序的一部分,我们称其为“ ProviderConfigurer”-其目标是加载服务(与META-INF / services / targetSPi打包在单独的jar中),而该服务又将加载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. 因此,要激活Archaius,您将需要放置2个罐子而不是一个,但是ProviderConfigurer将能够加载Service提供的属性源(API将是您必须定义的接口的一部分...)在类路径中会发现任何类,如果服务未找到实现您将为此目的定义的SPI的类,则不会执行任何操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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