问题
I'm trying to load a jar at runtime by URLClassLoader through Service Provider API. However, it turns out a failure.
Following are what I've done:
- Create a module named
shadow-plugin-api, which contains interfacecom.github.soiff.shadow.api.Pluginto be implemented by plugin; - Create a implementation of
shadow-plugin-apinamedshadow-pluginand packaged asshadow-plugin-0.0.1-SNAPSHOT.jar, the implementation class iscom.github.soiff.shadow.plugin.SpringPlugin; - Create spring boot application named
shadow-coreand includeshadow-plugin-api; - Load
shadow-plugin-0.0.1-SNAPSHOT.jarbyURLClassLoaderdynamically and try to load mycom.github.soiff.shadow.plugin.SpringPluginthroughServiceLoaderbut it gets nothing.
My git repository is : https://github.com/soiff/soiff-shadow.
I've tried following solution, but still could not make it work. Please give me some advice, thanks in advance!
- I've tried abstract class instead of interface of my SPI interface and change it back to interface when I could not achieve my goal;
- I've tried
PathMatchingResourcePatternResolverto get resource and pass myURLClassLoaderas the input parameter but it did not work; - I've tried
ResourceFinderimplemented by Apache and it could not find proper resource neither;
My question is how could I load resources from an external jar by URLClassLoader? Could SPI be a possible solution?
回答1:
To put it simple, the answer is yes.
And you may curious about what was going wrong, good question, the answer is URLClassLoader. But how? URLClassLoader is good enough to handle this with each items you've put it. In other words, there could be as many items as you've put into your URLClassLoader by parameter urls. So, if you want to make it work, you need to uncompress your external jar to a specified directory and add all items extracted to your URLClassLoader by input parameter urls as:
loader = new URLClassLoader(list.toArray(new URL[0]));
Where list contains all items.
Maybe there is other good solution, but this is just working for me. It's appreciate that if any guy could post another better solution for this. Thanks in advance!
By the way, this solution is based on Hadoop project. Thanks for the excellent project of Apache Hadoop Work Team.
来源:https://stackoverflow.com/questions/37337926/could-urlclassloader-be-approperiate-for-spi