-1
我有两个工作方式不同的项目。第一个用于类加载,第二个用于做一些处理工作。在运行时加载类时无法创建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类的第一个项目,然后它说, -
考虑您的 配置中定义类型“com.sample.Specific”的豆。
如何创建bean?
其实事情是我在运行时加载这个类,我只在那里声明包。你能否让我知道一些要点或代码来宣布我的豆类生活在哪里。因此,我不知道如何在运行时创建bean –
感谢您的合作lvan。这里的实际问题是:https://stackoverflow.com/questions/45115102/how-to-create-a-bean-at-runtime-at-the-time-while-using-class-loading-java-refl –
你能告诉我在context.xml参数标签之间声明了什么吗? –