Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing context:component-scan programatic way?

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?

like image 215
Xiè Jìléi Avatar asked Apr 07 '11 03:04

Xiè Jìléi


1 Answers

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);
}
like image 90
Benjamin Muschko Avatar answered Oct 01 '22 05:10

Benjamin Muschko