做上下文:组件扫描编程方式?

Xiè*_*léi 6 java spring annotations

我使用AnnotationConfigApplicationContextClasspathXmlApplicationContext当前混合,并AnnotationConfigApplicationContext作为父上下文.但我发现定义的bean AnnotationConfigApplicationContext不能很好地应对中定义的bean ClasspathXmlApplicationContext.所以我还是想放弃ClasspathXmlApplicationContext,AnnotationConfigApplicationContext只使我的应用程序使用.

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

任何的想法?

Ben*_*hko 5

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

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

public void addIncludeFilter(TypeFilter includeFilter) 
{
    this.scanner.addIncludeFilter(includeFilter);
}
Run Code Online (Sandbox Code Playgroud)