在运行时加载类时无法创建bean [英] Unable to create bean while loading class at runtime

查看:107
本文介绍了在运行时加载类时无法创建bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个工作方式不同的项目.第一个用于类加载,第二个具有用于执行某些处理工作的类.

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

}

}

正如我所提到的,这是两个不同的项目.因此,当我使用Main class运行第一个项目时,它说-

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

考虑在您的计算机中定义类型为"com.sample.Specific"的bean 配置.

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

如何创建bean?

推荐答案

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

This is because you are not able to find this class, into your component scan configuration you need to declare the package where your beans live.

这篇关于在运行时加载类时无法创建bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆