在动态加载的类中扫描组件

时间:2017-12-16 11:03:38

标签: java spring

我正在寻找扫描注册所有组件,在运行时使用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);

但是没有用,有没有实现呢?

1 个答案:

答案 0 :(得分:2)

经过搜索和尝试,这个工作

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