【发布时间】: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