Doing context:component-scan programatic way?

て烟熏妆下的殇ゞ 提交于 2019-12-30 09:22:08

问题


I'm mixed using AnnotationConfigApplicationContext and ClasspathXmlApplicationContext currently, and make AnnotationConfigApplicationContext as the parent context. But I found that beans defined in AnnotationConfigApplicationContext doesn't cope well with beans defined in ClasspathXmlApplicationContext. So I'd like to drop ClasspathXmlApplicationContext anyway, and make my application use AnnotationConfigApplicationContext only.

The problem is, I don't know how to replace <context:component-scan> totally. I can easily do a package scan using AnnotationConfigApplicationContext.scan(...), but there seems no way to add include/exclude pattern in AnnotationConfigApplicationContext.

Any idea?


回答1:


It doesn't look like the class AnnotationConfigApplicationContext provides exclusion/inclusion filters out-of-the-box. Internally the class uses an instance of ClassPathBeanDefinitionScanner to scan for annotations which provides the methods addExcludeFilter and addIncludeFilter. Unfortunately, the field is private and doesn't have a getter method so you can't just write an implementation that extends AnnotationConfigApplicationContext and add include and exclude methods. Instead you'll probably have to copy the code from AnnotationConfigApplicationContext and add the missing methods:

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

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


来源:https://stackoverflow.com/questions/5575470/doing-contextcomponent-scan-programatic-way

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