JavaとSpringBootのspiメカニズム



Spi Mechanism Java



springbootの自動アセンブリプロセスでは、META-INF / spring.factoriesファイルが最終的にロードされ、ロードプロセスはSpringFactoriesLoaderによってロードされます。 CLASSPATHの下の各JarパッケージからすべてのMETA-INF / spring.factories構成ファイルを検索し、プロパティファイルを解析して、指定された名前の構成を見つけて返します。実際、ClassPathパスの下で検索するだけでなく、すべてのパスの下でJarパッケージをスキャンするだけでなく、このファイルはClasspathの下のjarパッケージにのみ含まれることに注意してください。

public static final String FACTORIES_RESOURCE_LOCATION = 'META-INF/spring.factories' // The format of spring.factories file is: key=value1,value2,value3 // Find the META-INF/spring.factories file from all jar packages // Then parse out all the value values ​​of the key=factoryClass class name from the file public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) { String factoryClassName = factoryClass.getName() // Get the URL of the resource file Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) : ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION)) List<String> result = new ArrayList<String>() // Traverse all URLs while (urls.hasMoreElements()) { URL url = urls.nextElement() // Analyze the properties file according to the resource file URL to get a corresponding set of @Configuration classes Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url)) String factoryClassNames = properties.getProperty(factoryClassName) // Assemble the data and return result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames))) } return result }