Reputation: 5661
Is there a way to tell Spring to load classes from a given URL while instantiating the beans? I need to load classes from a location that is not in the classpath. If I were using pure Java, I could use URLClassLoader
but how can I achieve this in Spring? I am using Spring 3.0
Upvotes: 4
Views: 4109
Reputation: 51
public class Main {
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AutodeployConfiguration.class);
URL[] files = {
new File("C:\\module1.jar").toURL(),
new File("C:\\propertiesdirectory\\").toURL()
};
URLClassLoader plugin = new URLClassLoader(files, Main.class.getClassLoader());
Thread.currentThread().setContextClassLoader(plugin);
Class startclass = plugin.loadClass("de.module1.YourModule");
ExternalModule start = (ExternalModule) startclass.newInstance();
AnnotationConfigApplicationContext ivr = start.onDeploy(plugin, ctx);
}
}
public class YourModule implements ExternalModule {
@Override
public AnnotationConfigApplicationContext onDeploy(ClassLoader classloader, GenericApplicationContext parent) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.setClassLoader(classloader);
applicationContext.setParent(parent);
applicationContext.register(ModuleConcreteConfiguration.class);
applicationContext.refresh();
// other code
return applicationContext;
}
}
Upvotes: 0
Reputation: 12206
All Spring classes that extend DefaultResourceLoader
can have an explicit ClassLoader
reference set (via DefaultResourceLoader.setClassLoader(ClassLoader)
.
AbstractApplicationContext
happens to be one of those classes. So all ApplicationContext implementations that extend it (like ClassPathXmlApplicationContext
and FileSystemXmlApplicationContext
) can use an injected ClassLoader
reference.
Upvotes: 6