2016-11-10 20 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

相关问题