2012-01-19 88 views
3

有没有办法告诉Spring在实例化bean时从给定的URL加载类?我需要从不在类路径中的位置加载类。如果我使用纯Java,我可以使用URLClassLoader,但是我怎样在Spring中实现这一点?我使用Spring 3.0如何让Spring从给定的URL加载类(用于bean实例化)?

+2

什么['ClassPathXmlApplicationContext.setClassLoader()'](http://static.springsource.org/spring/docs/3.1.0.RELEASE/api/org/SP ringframework /核心/ IO/DefaultResourceLoader.html#setClassLoader(java.lang.ClassLoader的))? –

+0

看起来很有前途,但是应用程序上下文会使用这个类加载器来加载bean类吗?它当然会用它来加载applicationContext.xml文件中指定的资源。 – samitgaur

+2

查看[this](http://stackoverflow.com/questions/7968920)问题和...只是尝试:-)。 –

回答

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; 
    } 
} 
相关问题