Unable to create bean while loading class at runti

2020-03-31 06:11发布

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?

1条回答
太酷不给撩
2楼-- · 2020-03-31 06:51

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.

查看更多
登录 后发表回答