问题
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