I have an assignment wherein after creating a jar file using Spring Boot, I have to load it using URLClassLoader in a Java class to execute it. Issue is that although the jar file runs fine when launched directly but when I try to load it in a Java class using the following code, it fails.
public static void main(String[] args)
{
// Getting the jar URL which contains target class
URL[] classLoaderUrls = new URL[]{new URL("file:///C://Users\\CHH7KOR\\Documents\\POC\\BootDemo\\target\\BootDemo-0.0.1-SNAPSHOT.jar")};
// Create a new URLClassLoader
URLClassLoader urlClassLoader = new URLClassLoader(classLoaderUrls);
Thread.currentThread().setContextClassLoader(urlClassLoader);
System.out.println("ASHD:"+Thread.currentThread().getContextClassLoader());
// Load the target class
Class<?> beanClass = urlClassLoader.loadClass("sample.integration.SampleIntegrationApplication");
// 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("doAllFunctions");
method.invoke(beanObj);
}
The error that I get when I run this is:
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at Sample.main(Sample.java:33)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'ftpInboundChannel' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:698)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1175)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1060)
at sample.integration.SampleIntegrationApplication.doAllFunctions(SampleIntegrationApplication.java:57)
... 5 more
Here ftpInboundChannel is a channel configured as a part of spring-config.xml
来源:https://stackoverflow.com/questions/34611165/beans-not-recognized-from-spring-context-xml-while-loading-the-xml-file-as-a-par