提问者:小点点

如何在不使用spring-boot的情况下创建类似于“@ConditionalOnProperty”的自定义条件?


我试图使用spring context创建一个自定义条件。

  • 我正在使用Spring上下文 5.3.13(没有Spring引导)
  • 我在 src/main/resources 下有一个名为 config.yaml 的文件
  • 我有这个@PropertySource自定义配置:@PropertySource(value = “classpath:config.yaml”, factory = TypesafeAdapterPropertySourceFactory.class)
  • 我正在尝试从自定义Spring条件中获取属性:
public class MyConditionalOnProperty implements ConfigurationCondition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        // just to test what property sources are present
        for(Iterator it = ((AbstractEnvironment) context.getEnvironment()).getPropertySources().iterator(); it.hasNext(); ) {
            PropertySource propertySource = (PropertySource) it.next();
            System.out.println(propertySource.getName());
            //prints only "systemProperties" and "systemEnvironment"
        }
        
        return context.getEnvironment().containsProperty("my.prop");
    }

    @Override
    public ConfigurationPhase getConfigurationPhase() {
        return ConfigurationPhase.REGISTER_BEAN;
    }
}
  • 加载应用程序上下文后存在 my.prop
  • 我有一个带有条件注释的豆子:
@Named
@Singleton
@Conditional(PropertyEnabledCondition.class)
public class MyTestBean {

}

我还进行了调试,发现我的自定义属性源仅在这个阶段之后加载。

有没有办法在不使用 spring-boot 的情况下检索条件中的应用程序属性或重新创建@ConditionalOnProperty


共1个答案

匿名用户

问题是我的@Property tySource注释直接在我的应用程序的主配置类上,但在不同的配置上。这意味着它们仅在注册bean后才被处理。

所以如果你像这样开始你的上下文:

var context = new AnnotationConfigApplicationContext(SpringConfig.class);

确保您直接在< code>SpringConfig.java上注释了< code>@PropertySource