用编程的方式进行context:component-scan吗?

6
我目前混合使用AnnotationConfigApplicationContextClasspathXmlApplicationContext,并将AnnotationConfigApplicationContext设置为父上下文。但是我发现在ClasspathXmlApplicationContext中定义的bean与AnnotationConfigApplicationContext中定义的bean不兼容。所以无论如何,我想放弃使用ClasspathXmlApplicationContext,并让我的应用程序仅使用AnnotationConfigApplicationContext

问题是,我不知道如何完全替换<context:component-scan>。我可以使用AnnotationConfigApplicationContext.scan(...)轻松进行包扫描,但似乎没有办法在AnnotationConfigApplicationContext中添加包含/排除模式。

有什么想法吗?


还可以查看https://dev59.com/WHVC5IYBdhLWcg3wixw0 - Brian Laframboise
1个回答

5

看起来 AnnotationConfigApplicationContext 类并没有提供开箱即用的排除/包含过滤器。在内部,该类使用 ClassPathBeanDefinitionScanner 的一个实例来扫描注释,该实例提供了 addExcludeFilteraddIncludeFilter 方法。不幸的是,该字段是 private 的,并且没有 getter 方法,因此您不能只编写一个扩展 AnnotationConfigApplicationContext 并添加包含和排除方法的实现。相反,您可能需要从 AnnotationConfigApplicationContext 复制代码并添加缺少的方法:

public void addExcludeFilter(TypeFilter excludeFilter) 
{
    this.scanner.addExcludeFilter(excludeFilter);
}

public void addIncludeFilter(TypeFilter includeFilter) 
{
    this.scanner.addIncludeFilter(includeFilter);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接