How to filter a collection of beans using a collection of regex in Spring?

北城以北 提交于 2019-12-24 04:44:06

问题


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;
    }
}

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.

Any suggestion?


回答1:


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.



来源:https://stackoverflow.com/questions/28557646/how-to-filter-a-collection-of-beans-using-a-collection-of-regex-in-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!