国产成人精品久久免费动漫-国产成人精品天堂-国产成人精品区在线观看-国产成人精品日本-a级毛片无码免费真人-a级毛片毛片免费观看久潮喷

您的位置:首頁技術(shù)文章
文章詳情頁

Java SPI的簡單小實(shí)例

瀏覽:15日期:2022-08-29 13:27:02

JDK有個(gè)ServiceLoader類,在java.util包里,支持按約定目錄/META-INF/services去找到接口全路徑命名的文件,讀取文件內(nèi)容得到接口實(shí)現(xiàn)類的全路徑,加載并實(shí)例化。如果我們在自己的代碼中定義一個(gè)接口,別人按接口實(shí)現(xiàn)并打包好了,那么我們只需要引入jar包,通過ServiceLoader就能夠把別人的實(shí)現(xiàn)用起來。舉個(gè)例子,JDK中的JDBC提供一個(gè)數(shù)據(jù)庫連接驅(qū)動(dòng)接口,不同的廠商可以有不同的實(shí)現(xiàn),如果它們給的jar包里按規(guī)定提供了配置和實(shí)現(xiàn)類,那么我們就可以執(zhí)行不同的數(shù)據(jù)庫連接操作,比如MySql的jar包里就會(huì)有自己的配置:

Java SPI的簡單小實(shí)例

這里文件名就是接口:

Java SPI的簡單小實(shí)例

文件內(nèi)容是實(shí)現(xiàn)類:

Java SPI的簡單小實(shí)例

我們自己實(shí)現(xiàn)一個(gè)簡單例子,不需要打jar包,把目錄放到spring boot的resources下即可,這里就是classpath,跟你放jar包里效果一樣。

1、定義一個(gè)接口:

package com.wlf.service;public interface ITest { void saySomething();}

2、定義兩個(gè)實(shí)現(xiàn):

package com.wlf.service.impl;import com.wlf.service.ITest;public class ITestImpl1 implements ITest { @Override public void saySomething() { System.out.println('Hi, mia.'); }}

package com.wlf.service.impl;import com.wlf.service.ITest;public class ITestImpl2 implements ITest { @Override public void saySomething() { System.out.println('Hello, world.'); }}

3、按預(yù)定新增/META-INF/services/com.wlf.service.ITest文件:

com.wlf.service.impl.ITestImpl1com.wlf.service.impl.ITestImpl2

Java SPI的簡單小實(shí)例

4、定義一個(gè)執(zhí)行類,通過ServiceLoader加載并實(shí)例化,調(diào)用實(shí)現(xiàn)類方法,跑一下:

package com.wlf.service;import java.util.Iterator;import java.util.ServiceLoader;public class TestServiceLoader { public static void main(String[] args) { ServiceLoader<ITest> serviceLoader = ServiceLoader.load(ITest.class); Iterator<ITest> iTests = serviceLoader.iterator(); while (iTests.hasNext()) { ITest iTest = iTests.next(); System.out.printf('loading %sn', iTest.getClass().getName()); iTest.saySomething(); } }}

打印結(jié)果:

Java SPI的簡單小實(shí)例

ServiceLoader源碼比較簡單,可以看下上面我們使用到的標(biāo)黃了的方法:

/** * Lazily loads the available providers of this loader’s service. * * <p> The iterator returned by this method first yields all of the * elements of the provider cache, in instantiation order. It then lazily * loads and instantiates any remaining providers, adding each one to the * cache in turn. * * <p> To achieve laziness the actual work of parsing the available * provider-configuration files and instantiating providers must be done by * the iterator itself. Its {@link java.util.Iterator#hasNext hasNext} and * {@link java.util.Iterator#next next} methods can therefore throw a * {@link ServiceConfigurationError} if a provider-configuration file * violates the specified format, or if it names a provider class that * cannot be found and instantiated, or if the result of instantiating the * class is not assignable to the service type, or if any other kind of * exception or error is thrown as the next provider is located and * instantiated. To write robust code it is only necessary to catch {@link * ServiceConfigurationError} when using a service iterator. * * <p> If such an error is thrown then subsequent invocations of the * iterator will make a best effort to locate and instantiate the next * available provider, but in general such recovery cannot be guaranteed. * * <blockquote style='font-size: smaller; line-height: 1.2'><span * style='padding-right: 1em; font-weight: bold'>Design Note</span> * Throwing an error in these cases may seem extreme. The rationale for * this behavior is that a malformed provider-configuration file, like a * malformed class file, indicates a serious problem with the way the Java * virtual machine is configured or is being used. As such it is * preferable to throw an error rather than try to recover or, even worse, * fail silently.</blockquote> * * <p> The iterator returned by this method does not support removal. * Invoking its {@link java.util.Iterator#remove() remove} method will * cause an {@link UnsupportedOperationException} to be thrown. * * @implNote When adding providers to the cache, the {@link #iterator * Iterator} processes resources in the order that the {@link * java.lang.ClassLoader#getResources(java.lang.String) * ClassLoader.getResources(String)} method finds the service configuration * files. * * @return An iterator that lazily loads providers for this loader’s * service */ public Iterator<S> iterator() { return new Iterator<S>() { Iterator<Map.Entry<String,S>> knownProviders= providers.entrySet().iterator(); public boolean hasNext() {if (knownProviders.hasNext()) return true;return lookupIterator.hasNext(); } public S next() {if (knownProviders.hasNext()) return knownProviders.next().getValue();return lookupIterator.next(); } public void remove() {throw new UnsupportedOperationException(); } }; }

我們用到的迭代器其實(shí)是一個(gè)Map:

// Cached providers, in instantiation order private LinkedHashMap<String,S> providers = new LinkedHashMap<>();

它用來緩存加載的實(shí)現(xiàn)類,真正執(zhí)行的是lookupIterator:

// The current lazy-lookup iterator private LazyIterator lookupIterator;

我們看下它的hasNext和next方法:

public boolean hasNext() { if (acc == null) {return hasNextService(); } else {PrivilegedAction<Boolean> action = new PrivilegedAction<Boolean>() { public Boolean run() { return hasNextService(); }};return AccessController.doPrivileged(action, acc); } } public S next() { if (acc == null) {return nextService(); } else {PrivilegedAction<S> action = new PrivilegedAction<S>() { public S run() { return nextService(); }};return AccessController.doPrivileged(action, acc); } }

private boolean hasNextService() { if (nextName != null) {return true; } if (configs == null) {try { String fullName = PREFIX + service.getName(); if (loader == null) configs = ClassLoader.getSystemResources(fullName); else configs = loader.getResources(fullName);} catch (IOException x) { fail(service, 'Error locating configuration files', x);} } while ((pending == null) || !pending.hasNext()) {if (!configs.hasMoreElements()) { return false;}pending = parse(service, configs.nextElement()); } nextName = pending.next(); return true; } private S nextService() { if (!hasNextService())throw new NoSuchElementException(); String cn = nextName; nextName = null; Class<?> c = null; try {c = Class.forName(cn, false, loader); } catch (ClassNotFoundException x) {fail(service, 'Provider ' + cn + ' not found'); } if (!service.isAssignableFrom(c)) {fail(service, 'Provider ' + cn + ' not a subtype'); } try {S p = service.cast(c.newInstance());providers.put(cn, p);return p; } catch (Throwable x) {fail(service, 'Provider ' + cn + ' could not be instantiated', x); } throw new Error(); // This cannot happen } public boolean hasNext() { if (acc == null) {return hasNextService(); } else {PrivilegedAction<Boolean> action = new PrivilegedAction<Boolean>() { public Boolean run() { return hasNextService(); }};return AccessController.doPrivileged(action, acc); } }

hasNext查找實(shí)現(xiàn)類,并指定了類路徑:

private static final String PREFIX = 'META-INF/services/';

具體查找操作看這里:

pending = parse(service, configs.nextElement());

next則是實(shí)例化加載到的實(shí)現(xiàn)類,使用反射Class.forName加載類、newInstance實(shí)例化對象。

以上就是Java SPI的簡單小實(shí)例的詳細(xì)內(nèi)容,更多關(guān)于Java SPI實(shí)例的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: Java
相關(guān)文章:
主站蜘蛛池模板: yellow中文字幕久久网 | 亚洲精品第五页 | 久久久午夜精品理论片 | 国产精品亚洲视频 | 美国全免费特一级毛片 | 国产大秀视频 | 国产亚洲精品看片在线观看 | 亚洲天堂日韩在线 | 亚洲欧美精品中文字幕 | 在线看黄网址 | 大尺度福利视频奶水在线 | 99re思思| 美女被cao免费看在线看网站 | 亚洲精品自拍 | 亚洲人成综合网站在线 | 影音先锋色先锋女同另类 | 久久国产精品-久久精品 | 日韩三级免费观看 | 日本一级特黄特色大片免费视频 | 99re66热这里只有精品免费观看 | 亚洲成a人片毛片在线 | 精品国产免费观看久久久 | 亚洲人的天堂男人爽爽爽 | 亚洲欧美一区二区久久香蕉 | 一级毛片一级毛片一级毛片 | 精品久久久久久中文字幕 | 大视频在线爱爱爱爱 | 日本中文字幕不卡免费视频 | 国产日产久久高清欧美一区 | 欧美激情成人网 | 男人免费看片 | 久久91这里精品国产2020 | 欧美精品久久天天躁 | 亚洲另类在线视频 | 国产a级特黄的片子视频 | 色日韩| 国产精品1页 | 毛片免费全部免费播放 | 一区二区三区四区视频 | 欧美一区二三区 | 欧美 自拍 |