我试图使用spring context创建一个自定义条件。
上下文 5.3.13
(没有Spring引导)src/main/resources
下有一个名为 config.yaml
的文件@PropertySource
自定义配置:@PropertySource(value = “classpath:config.yaml”, factory = TypesafeAdapterPropertySourceFactory.class)
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
?
问题是我的@Property tySource
注释直接在我的应用程序的主配置类上,但在不同的配置上。这意味着它们仅在注册bean后才被处理。
所以如果你像这样开始你的上下文:
var context = new AnnotationConfigApplicationContext(SpringConfig.class);
确保您直接在< code>SpringConfig.java上注释了< code>@PropertySource