简体   繁体   中英

Unable to create bean while loading class at runtime

I have two projects which works differently. First one is used for class loading and second one has its class which is used for doing some processing work.

In first project I am loading the class and instead of creating new instance for invoking the method I am only using application context.

@Autowired
ApplicationContext context;

ClassLoader loader = null;

try {
    loader = URLClassLoader.newInstance(new URL[]{new   

File(plugins + "/" + pluginName + "/" + pluginName +   

".jar").toURI().toURL()}, getClass().getClassLoader());

} catch (MalformedURLException e) {
    e.printStackTrace();
}

Class<?> clazz = null;

try {

    clazz = Class.forName("com.sample.Specific", true, loader);

} catch (ClassNotFoundException e) {

    e.printStackTrace();

}

Method method = null;
try {
    method = clazz.getMethod("run",new Class[]{});
} catch (NoSuchMethodException e) {
    e.printStackTrace();
}

try {
    method.invoke(context.getBean(clazz),new Object[]{});
} catch (IllegalAccessException e) {
    e.printStackTrace();
} catch (InvocationTargetException e) {
    e.printStackTrace();
}

In Second Project I have this example :

package com.sample

@Service
public class Specific {

@Autowired
private FD fd;


public void run(){

    fd.init();

}

}

As I have mentioned these are two different projects. So when I run the first project with Main class , then it says that --

Consider defining a bean of type 'com.sample.Specific' in your configuration.

How can I create the bean?

这是因为您无法找到此类,因此在组件扫描配置中需要声明Bean所在的软件包。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM