在运行时加载类时无法创建bean

xpcnnkqh  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(311)

我有两个工作方式不同的项目。第一个用于类加载,第二个有自己的类用于执行一些处理工作。
在第一个项目中,我加载类,而不是创建新示例来调用方法,我只使用应用程序上下文。

@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();
}

在第二个项目中,我有一个例子:

package com.sample

@Service
public class Specific {

@Autowired
private FD fd;

public void run(){

    fd.init();

}

}

正如我提到的,这是两个不同的项目。所以当我用main类运行第一个项目时,它会说--
考虑在配置中定义类型为“com.sample.specific”的bean。
如何创建bean?

toe95027

toe950271#

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

相关问题