【问题标题】:How to filter a collection of beans using a collection of regex in Spring?如何在 Spring 中使用正则表达式集合过滤 bean 集合?
【发布时间】:2015-02-17 08:30:15
【问题描述】:

我想在注释模式下使用Spring 自动装配一组bean。我已经尝试过类似下面的方法...

@Configuration
@ComponentScan(basePackages = "mypkg", 
    includeFilters = @Filter(type = FilterType.REGEX, pattern = {"regex1", "regex2"}), 
    excludeFilters = @Filter(type = FilterType.REGEX, pattern = "regex3"))
public class BeanCollector {

    @Autowired
    private List<MyBean> myBeans;

    @Bean(name = "beans")
    public List<MyBean> getMyBeans() {
        return myBeans;
    }
}

这段代码运行良好,但问题是在我的应用程序的现实世界中。 regexes 是在运行时生成的,所以我不能将它们硬编码为上面的代码。我使用了一个带有静态方法的类,它返回一个这样的字符串数组......

includeFilters = @Filter(type = FilterType.REGEX, pattern = Regexes.getIncludeRegexes())

但它会带来编译错误。我认为它应该有一个解决方案,但尽管进行了深入的谷歌搜索,我还是找不到任何解决方案。

有什么建议吗?

【问题讨论】:

  • 这种方法(使用注解和Regexes.getIncludeRegexes() 将不起作用,因为Java 中的注解需要编译时常量来表示它们的属性值,而不是表达式。您必须考虑一些基于反射的方法,恕我直言。
  • @kocko 谢谢,我怀疑注解属性的值是否在编译时处理。

标签: java spring dependency-injection autowired


【解决方案1】:

如果我理解正确,您希望动态选择一组与MyBean 类/接口匹配的可用bean。最好的方法是像上面那样注入Collection&lt;MyBean&gt;,然后迭代集合,根据您的标准进行选择。 Groovy 闭包、Google Guava 或 Java 8 lambda 可以使该过程更易于编写。

【讨论】:

  • 我现在在自动装配的 bean 上使用迭代并过滤所需的 bean,但是这种方法会产生垃圾(即不需要的 bean 会变成垃圾)。这就是为什么我正在寻找一种方法来避免创建不需要的 bean。无论如何,我很想知道如何使用Groovy closuresGoogle GuavaJava 8 lambdasCollection 进行迭代。可以给我一个sn-p代码吗?
  • @faghani 那么也许您想要的是工厂或 SPI,因为您的过滤器方法仍会将所有 bean 留在上下文中(甚至不是垃圾,这没关系)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-21
  • 2011-11-28
  • 1970-01-01
  • 2020-11-24
  • 1970-01-01
  • 2014-01-04
相关资源
最近更新 更多