Java 自动关联筛选列表

Java 自动关联筛选列表,java,spring,spring-boot,autowired,spring-java-config,Java,Spring,Spring Boot,Autowired,Spring Java Config,我有一个接口(组件)的多个实现(ComponentA、ComponentB、ComponentC),需要根据属性文件提供的属性自动连接到配置类(MyConfiguration) 真菌配置类 @Configuration @PropertySource("classpath:settings.properties") public class MyConfiguration implements ConfigurationService { @Value("#{'${enabled.compon

我有一个接口(组件)的多个实现(ComponentA、ComponentB、ComponentC),需要根据属性文件提供的属性自动连接到配置类(MyConfiguration)

真菌配置类

@Configuration
@PropertySource("classpath:settings.properties")
public class MyConfiguration implements ConfigurationService {

@Value("#{'${enabled.components}'.split(',')}")
private Set<String> enabledComponentQualifiers;

@Autowired
private Set<Component> enabledComponentSet;
...
设置.property文件

enabled.components=componenta,componentb
我希望自动连线集(上面的enabledComponentSet)只包括在enabled.components属性中过滤的组件


使用JavaConfig的最佳方法是什么?

在上面的示例中,您只想将ComponentA和ComponentB注入集合中。在这种情况下,实例化ComponentC是否仍然很重要?如果没有,那么您可以使用一个条件来防止创建不需要的组件实现,然后将组件bean连接到集合中只需注入所有可用的组件bean即可不实例化排除的组件,因为在应用程序的整个生命周期中不需要它们。因此,我同意你的建议。我试试看,然后告诉你。谢谢在组件实现中设置
@ConditionalOnExpression(“${enabled.components}.contains('componenta')”)
确实起到了作用,但是我不得不在application.properties文件中包含enabled.components=componenta,componentb属性。即使配置类有
@PropertySource(“classpath:settings.properties”)
,在条件评估期间它似乎不可用。有没有办法让settings.properties@CraigWalls有效?我刚刚尝试了一下,重新创建了你的设置(尽可能接近你的项目源代码),它对我来说很好。简而言之,我让Initializer给了我一个SpringMVC和执行器的起点。我创建了一个启用了
的settings.properties.components,如您所述。我创建了一个用
@Component
注释的
ComponentA
类,与您的
@ConditionalOnExpression
相同。我还向
组件a
构造函数添加了一些sysout,以便在启动时看到它被创建。最后,我用
@PropertySource
注释了引导类。实际上,
@PropertySource
是Spring Boot的特殊属性源(请参阅)考虑的属性源之一,所以我看不出它不起作用的原因。
enabled.components=componenta,componentb