Using ClassPathScanningCandidateComponentProvider with multiple jar files?

你说的曾经没有我的故事 提交于 2019-12-04 10:50:57

问题


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


回答1:


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);

...


来源:https://stackoverflow.com/questions/8807388/using-classpathscanningcandidatecomponentprovider-with-multiple-jar-files

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