如何在Spring中使用正则表达式集合过滤bean集合? [英] How to filter a collection of beans using a collection of regex in Spring?

查看:397
本文介绍了如何在Spring中使用正则表达式集合过滤bean集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在注释模式下使用Spring自动装配一个bean集合.我已经尝试过类似下面的内容...

I want to autowire a collection of beans using Spring in annotaion mode. I've tried this something like the below ...

@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是在运行时生成的,因此我不能像上面的代码那样对它们进行硬编码.我使用了带有静态方法的类,该方法返回了这样的String数组...

This code works pretty well, but the problem is that in real world of my app. the regexes are generated in runtime, so I can't hardcode them as the code above. I used a class with a static method returning a String array like this ...

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

但是它带来了编译错误.我认为应该有一个解决方案,但是尽管深入研究,我还是找不到任何解决办法.

But it brings compile error. I think it ought to have a solution but in spite of a deep googling I couldn't find any.

有什么建议吗?

推荐答案

如果我对您的理解正确,那么您希望动态选择一些与MyBean类/接口匹配的可用Bean.最好的方法是在执行上述操作时注入Collection<MyBean>,然后遍历集合,并根据您的条件进行选择. Groovy闭包,Google Guava或Java 8 lambda可以使该过程更易于编写.

If I understand you correctly, you're wanting to dynamically select some set of the available beans that match the MyBean class/interface. The best way to do that is to inject a Collection<MyBean> as you're doing above and then iterate over the collection, selecting according to your criteria. Groovy closures, Google Guava, or Java 8 lambdas can make that process simpler to write.

这篇关于如何在Spring中使用正则表达式集合过滤bean集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆