1

看Springboot源码的时候,SpringFactoriesLoader类中loadFactoryNames方法里:

public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
        String factoryClassName = factoryClass.getName();
        try {
            Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
                    ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
            List<String> result = new ArrayList<String>();
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
                String factoryClassNames = properties.getProperty(factoryClassName);
                result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
            }
            return result;
        }

当添加了springboot-devtools依赖后classLoader.getResources(FACTORIES_RESOURCE_LOCATION)加载的是spring-boot-devtools包中的META-INF/spring.factories文件,而去掉devtools的依赖之后加载的是spring-boot包中的META-INF/spring.factories文件,这是怎么实现的?为什么会这样?

sean 33
2017-12-28 提问
1 个回答
1

Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION):ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
如果是spring-boot-devtools 这里的classloader是RestartClassLoader 所以加载的都是
spring-boot-devtools包中的META-INF/spring.factories文件中的类


刚刚又看了一下 发现都会加载的好像,所有的jar包下的META-INF/spring.factories都会加载
但是spring-boot-devtools 使用的类加载器是RestartClassLoader

撰写答案

推广链接