gpt4 book ai didi

java - 扫描动态加载类中的组件

转载 作者:搜寻专家 更新时间:2023-11-01 03:16:40 25 4
gpt4 key购买 nike

正在寻找扫描注册所有组件,在运行时使用URLClassLoader加载jar文件后,jar文件只包含用 @Component 等注释的类 ...我试过了

GenericBeanDefinition bd = new GenericBeanDefinition();
bd.setBeanClass(MyClass.class);
beanFactory.registerSingleton("myBean", bd);

ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) ctx).getBeanFactory();
beanFactory.createBean(MyClass.class);

但没有奏效,是否有办法实现这一目标?

最佳答案

经过搜索和尝试,这个方法成功了

public Class<?> loadAllJarClasses(String pathToJar, String mainClassName) {

Class<?> clazz = null;
Class c;

try {

JarFile jarFile = new JarFile(pathToJar);
Enumeration<JarEntry> e = jarFile.entries();

URL[] urls = { new URL("jar:file:" + pathToJar + "!/") };
URLClassLoader cl = URLClassLoader.newInstance(urls);

while (e.hasMoreElements()) {
JarEntry je = e.nextElement();
if (je.isDirectory() || !je.getName().endsWith(".class")) {
continue;
}
// -6 because of .class
String className = je.getName().substring(0, je.getName().length() - 6);
className = className.replace('/', '.');
logger.info("loading " + className);
c = cl.loadClass(className);
resgisterBean(c);
logger.info("loaded " + className);
if (className.equalsIgnoreCase(mainClassName))
clazz = c;

}
} catch (Exception e) {
e.printStackTrace();
}
return clazz;
}

public void resgisterBean(Class<?> clazz) {

beanFactory = (BeanDefinitionRegistry) ((ConfigurableApplicationContext) ctx)
.getBeanFactory();

beanFactory.registerBeanDefinition(clazz.getName(),
BeanDefinitionBuilder.genericBeanDefinition(clazz).getBeanDefinition());
}

关于java - 扫描动态加载类中的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47844970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com