4

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

4
  • 2
    What about ClassPathXmlApplicationContext.setClassLoader()? Commented Jan 19, 2012 at 22:22
  • Looks promising, but will the application context use this class loader to load bean classes? It certainly will use it to load resources specified in an applicationContext.xml file. Commented Jan 19, 2012 at 22:32
  • 2
    See this question and... just try it :-). Commented Jan 19, 2012 at 22:35
  • Thanks Tomasz, I think this is the solution. Commented Jan 19, 2012 at 22:47

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Dev. Thanks to Tomasz as well who suggested the same solution in the question comments.
0
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; } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.