在运行时加载jar后动态加载spring组件

时间:2018-09-30 23:31:51

标签: spring spring-boot jar

在运行时加载JAR文件后,我试图将spring组件加载到我的上下文中。 目前正在使用幼稚的方法

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

                if (c.getAnnotation(org.springframework.stereotype.Component.class) != null
                        || c.getAnnotation(org.springframework.stereotype.Service.class) != null) {
                    resgisterBean(c);
                    logger.info("registered bean for " + c.getName());
                }

                if (className.equalsIgnoreCase(mainClassName)) {
                    clazz = c;
                }

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

RegisterBean函数

public void resgisterBean(Class<?> clazz) {

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

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

    }

我也尝试过applicationContext.refresh(),但收到一条错误消息,指出generic applicationContext can be refreshed only once 有没有更清洁的方法可以做到这一点?

0 个答案:

没有答案