【发布时间】:2018-07-20 21:13:40
【问题描述】:
似乎 ConditionalOnProperty 仅适用于类路径中的属性,例如资源文件夹中的 application.properties。我需要一个最终用户可以通过外部属性打开和关闭的属性。一个例子非常简单:
配置类,读取外部属性。 Sys.out 以显示它正在正确读取文件。
@Configuration
@EnableAutoConfiguration
@PropertySource("file:/Users/end.user/MyApp/config/MyApp.properties")
public class PropertyConfigurer {
@Value("${featureOne}")
private String featureOne;
@PostConstruct
public void init() {
System.out.println("FeatureOne : " + featureOne);
}
}
Feature 类,如果通过 ConditionalOnProperty 启用该属性,则该组件类将被放入应用程序上下文中以便能够使用,否则永远不会实例化该组件。
@Component
@ConditionalOnProperty(name="featureOne", havingValue = "true")
public class FeatureOne {
@PostConstruct
public void init() {
System.out.println("Feature initialized");
}
}
你可以想象我从来没有看到“功能初始化”,因为“featureOne”属性直到这个类被构造之后才可用于spring上下文。如果有某种方法可以强制 @PropertySource 中的属性在类实例化时可用于 spring 上下文。还是有什么其他方式?我还尝试了 FeatureOne 中的 @DependsOn PropertyConfigurer,但有趣的是,这也没有用。
【问题讨论】:
标签: java spring spring-boot properties configuration