Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ClassPathScanningCandidateComponentProvider with multiple jar files?

I'm looking at using ClassPathScanningCandidateComponentProvider for finding sub-classes of a specific Class in my JVM.

I'm doing pretty much exactly what is described here: Scanning Java annotations at runtime

However, when I call the code from ant, via a JMX bean I hit a serious issue.

I call: ClassPathScanningCandidateComponentProvider.findCandidateComponents with the search package: "com.mycompany"

However, there are multiple jar files in my classpath that contain classes that start with that package. Spring is stopping scanning after the first one is scanned (I know this as if I search for sublasees of java.lang.Object I get all classes in one jar file).

Is there a way to tell ClassPathScanningCandidateComponentProvider/Spring not to stop scanning after the first jar ?

Cheers

like image 610
Ro. Avatar asked Jan 10 '12 17:01

Ro.


1 Answers

Turns out that I hads to explicitly define the ClassLoader, since when running the scan from JMX, it will look for classes on a different loader and find nothing

//Add that at top of class
private static final ClassLoader classLoader = MyClass.class.getClassLoader();

...

ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider( true);

provider.addIncludeFilter(new AssignableTypeFilter(forClass));

//Had to add this line
provider.setResourceLoader(new PathMatchingResourcePatternResolver(classLoader));

final Set<BeanDefinition> candidates = provider.findCandidateComponents(SEARCH_PACKAGE);

...
like image 107
Ro. Avatar answered Oct 14 '22 09:10

Ro.