2012-01-19 6 views
3

Beanをインスタンス化している最中に、指定されたURLからクラスをロードするようにSpringに指示する方法はありますか?クラスパスにない場所からクラスをロードする必要があります。純粋なJavaを使用していた場合、URLClassLoaderを使用できますが、これをSpringでどのように達成できますか?私は春の3.0特定のURLからBeanインスタンス化のためのSpringロードクラスを作成するにはどうすればよいですか?

+2

を[ 'ClassPathXmlApplicationContext.setClassLoader()'](http://static.springsource.org/spring/docs/3.1.0.RELEASE/api/org/sp ringframework/core/io/DefaultResourceLoader.html#setClassLoader(java.lang.ClassLoader))? –

+0

有望ですが、アプリケーションコンテキストはこのクラスローダーを使用してBeanクラスをロードしますか? applicationContext.xmlファイルで指定されたリソースをロードするためには、必ずそれを使用します。 – samitgaur

+2

[this](http://stackoverflow.com/questions/7968920)の質問と...ちょうどそれを試してみてください:-)。 –

答えて

4

を使用してDefaultResourceLoaderを拡張するすべての春のクラスはDefaultResourceLoader.setClassLoader(ClassLoader)を経由して、明示的ClassLoader参照セットを(持つことができています。

AbstractApplicationContextは、これらのクラスの1つであることを起こる。それを拡張するので、すべてのApplicationContextの実装(のようなClassPathXmlApplicationContextFileSystemXmlApplicationContext)注入ClassLoader基準を使用することができる。何約

+0

ありがとうございます。 Tomaszのおかげで誰が質問のコメントに同じ解決策を提案しましたか。 – samitgaur

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; 
    } 
}