2016-11-10 62 views
3

我有這樣的代碼:裝載所有它的組件類從outter罐子

// Getting the jar URL which contains target class 
    URL[] classLoaderUrls = new URL[]{new URL("LINKTOJAR")}; 

    // Create a new URLClassLoader 
    URLClassLoader urlClassLoader = new URLClassLoader(classLoaderUrls); 

    // Load the target class 
    Class<?> beanClass = urlClassLoader.loadClass("com.my.class"); 

    // Create a new instance from the loaded class 
    Constructor<?> constructor = beanClass.getConstructor(); 
    Object beanObj = constructor.newInstance(); 

    // Getting a method from the loaded class and invoke it 
    Method method = beanClass.getMethod("sayHello"); 
    method.invoke(beanObj); 

它應該調用需要一個bean來工作sayHello方法。

該方法打印「Hello%Name」,其中名稱是@AutoWired字符串。

該方法的調用正在工作,但問題在於它只是說「你好」,因爲該字符串不是自動裝配的,而且是「空」。

如何使這個Autowired成爲可能,如果所有的上下文都在我調用的jar中,並且似乎沒有被加載?

謝謝。

編輯::

的想法是有這樣的:

ApplicationContext context = new ClassPathXmlApplicationContext(
     "classpath*:**/applicationContext*.xml"); 

MyAdder myAdder = (MyAdder) context.getBean("myAdder"); 

爲了加載的背景下,但我不知道如何從outter罐子加載此背景下。

回答

0

你會如何期待它的工作,因爲Spring不知道你的外部類 - 它超出了應用程序的上下文。注入確實看起來像「魔術」,但它只是由Spring容器完成。

你將不得不使用自己的應用程序上下文,並獲取bean「春天的方式」。

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html

的一種方式將是用你需要注入串到你的當前上下文,並把它作爲參數傳遞給方法。另一個更多的「注入風格」方法是使用反射來設置字符串 - 這或多或少是由Spring容器在內部完成的。

+2

是的,這是一個問題,我如何加載外部jar的上下文,以便完成這項工作。問題是,不只是注入字符串,想象的字符串來自一個數據庫,配置了MyBatis ...我需要這個邏輯來加載,但我不能看到執行de jar的方式擁有所有工作 –

+0

您可以嘗試使用現有應用程序上下文的自動裝配。 http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/config/AutowireCapableBeanFactory.html – Antoniossss

相關問題