有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有两个不同的项目。第一个用于类加载,第二个有自己的类,用于执行一些处理工作

在第一个项目中,我加载类,而不是创建新实例来调用该方法,我只使用应用程序上下文

@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类运行第一个项目时,它说--

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

如何创建bean


共 (1) 个答案

  1. # 1 楼答案

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