我有这个代码:
// 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 字符串。
对该方法的调用正在工作,但问题是它只是说“Hello”,因为字符串没有被 Autowiring ,并且它是“null”。
如果所有上下文都在我正在调用的 jar 中并且似乎没有加载,我怎样才能使这个 Autowired 成为可能?
谢谢。
编辑::
这个想法是有类似的东西:
ApplicationContext context = new ClassPathXmlApplicationContext(
"classpath*:**/applicationContext*.xml");
MyAdder myAdder = (MyAdder) context.getBean("myAdder");
为了加载上下文,但我不知道如何从外部 jar 加载此上下文。
最佳答案
您希望它如何工作,因为 Spring 不知道您的外部类 - 它超出了应用程序上下文。注入(inject)确实看起来像“魔法”,但它只是由 Spring 容器完成的。
您必须使用自己的应用程序上下文,并以“Spring 方式”获取 bean。
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html
一种解决方法是将所需的字符串注入(inject)到当前上下文中,并将其作为参数传递给方法。
另一种更“注入(inject)风格”的方法是使用反射自行设置字符串 - 这或多或少是 Spring 容器内部完成的方式。
关于java - 从外部 jar 加载一个类及其所有组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40525188/