2012-01-19 63 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; 
    } 
} 
相關問題