上一篇文章中APT技術(shù)的基本使用中用到了AutoService(https://github.com/google/auto) 這個(gè)框架,那么為什么我們寫了一個(gè)AnnotationProcessor之后抹沪,再加一個(gè)@AutoService(Processor.class)注解洋闽,在javac的過(guò)程中就會(huì)執(zhí)行我們的AnnotationProcessor呢?
首先需要了解一下SPI的開發(fā)模式休涤。
SPI
簡(jiǎn)介
SPI(Service Provider Interface)咱圆,SPI技術(shù)就是可以根據(jù)某個(gè)接口找到其實(shí)現(xiàn)類,然后根據(jù)不同的業(yè)務(wù)場(chǎng)景使用不同的實(shí)現(xiàn)類。比如我們現(xiàn)在有一個(gè)的Login登錄功能序苏,然后針對(duì)不同的渠道包需要用不同的實(shí)現(xiàn)手幢。 一般情況我們會(huì)創(chuàng)建一個(gè)Login對(duì)外的接口,比如LoginService忱详,內(nèi)容大概如下:
public class LoginService {
public static void login(String userName弯菊,String password) {
if (渠道 == A) {
useLoginAImpl(userName,password)
} else if (渠道 == B) {
useLoginBImpl(userName踱阿,password)
}
}
}
這樣子管钳,假如我們的渠道包的映射關(guān)系發(fā)生了變化的話我們就需要來(lái)修改這部分代碼,并且兩份實(shí)現(xiàn)都會(huì)被打入apk中软舌。所以這個(gè)時(shí)候就可以使用到SPI設(shè)計(jì)了才漆,下面通過(guò)一個(gè)demo來(lái)了解一下SPI的基本使用。
demo
demo主要分為api模塊佛点,里面主要是接口醇滥;然后還有連個(gè)實(shí)現(xiàn)模塊functionA,functionB分別實(shí)現(xiàn)了api接口超营。最后app模塊使用這個(gè)接口鸳玩。
api module
這是一個(gè)java library工程,我們?cè)诶锩娑x一個(gè)接口IFunction
public interface IFunction {
String getName();
void doFunction();
}
functinA module
這也是一個(gè)java library工程演闭,這里我們實(shí)現(xiàn)api module中定義的接口不跟。
@AutoService(IFunction.class)
public class FunctionA implements IFunction {
@Override
public String getName() {
return "FunctionA";
}
@Override
public void doFunction() {
}
}
可以看到我們?cè)谶@個(gè)類上面添加了@AutoService(IFunction.class)的注解修飾。build.gradle文件需要添加以下依賴關(guān)系:
api 'com.google.auto.service:auto-service:1.0-rc6'
annotationProcessor 'com.google.auto.service:auto-service:1.0-rc6'
implementation project(":api")
functionB module
functionB module和functionA module是一樣的米碰,這里就不展開了窝革。
app module
build.gradle 中需要添加以下依賴:
implementation project(":api")
annotationProcessor 'com.google.auto.service:auto-service:1.0-rc6'
implementation project(":functionA")
implementation project(":functionB")
然后我們就可以在代碼中通過(guò)ServiceLoader找到我們的具體實(shí)現(xiàn)類了。
private fun loadServices() {
ServiceLoader.load(IFunction::class.java).forEach {
Log.i("MainActivity", "function class = " + it::class.java + " function name = " + it.name)
}
}
這段代碼跑起來(lái)會(huì)打印出我們的IFunction接口的兩個(gè)實(shí)現(xiàn)類吕座。這樣子我們就可以使用到這兩個(gè)實(shí)現(xiàn)類了虐译。
假如說(shuō)我們現(xiàn)在只需要使用到A實(shí)現(xiàn),那么我們的app module就依賴Amodule吴趴,如果要使用到B實(shí)現(xiàn)漆诽,那么就依賴Bmodule,就避免了編碼的修改與多余代碼的打包锣枝。并且模塊的耦合度進(jìn)一步降低厢拭。更多代碼詳情請(qǐng)見demo (https://github.com/huanghuanhuanghuan/SPIDemo.git)
原理
那么demo的實(shí)現(xiàn)原理是什么呢?我們都知道我們使用@AutoService(IFunction.class)修飾后惊橱,在編譯打成jar包的時(shí)候就會(huì)生成META-INF.services文件夾蚪腐。然后其中會(huì)有以我們的注解中的class全路徑命名的文件,文件內(nèi)部有其實(shí)現(xiàn)類税朴。就上面demo的例子來(lái)說(shuō)就會(huì)有一個(gè)com.example.api.IFunction的文件回季,functionA module中的這個(gè)文件內(nèi)容就是com.example.functiona.FunctionA家制,而functionB module中的內(nèi)容則是:com.example.functiona.FunctionB。
而對(duì)于app module來(lái)說(shuō)的話則會(huì)把這兩個(gè)都合并到一起泡一。我們可以拆開apk看一下颤殴,就會(huì)發(fā)現(xiàn)com.example.api.IFunction文件的內(nèi)容為:
com.example.functionb.FunctionB
com.example.functiona.FunctionA
所以說(shuō)AutoService的工作就是在META-INF.services文件夾中創(chuàng)建一個(gè)以接口類名為文件名,所有的接口實(shí)現(xiàn)類全名保存在其中的一個(gè)key - list 的映射鼻忠。
而ServiceLoader則是java提供的一個(gè)api涵但。主要是用來(lái)讀取解析而這個(gè)key - list 的映射關(guān)系的。
public static <S> ServiceLoader<S> load(Class<S> service) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
return ServiceLoader.load(service, cl);
}
public static <S> ServiceLoader<S> load(Class<S> service,
ClassLoader loader)
{
return new ServiceLoader<>(service, loader);
}
public void reload() {
providers.clear();
lookupIterator = new LazyIterator(service, loader);
}
private ServiceLoader(Class<S> svc, ClassLoader cl) {
service = Objects.requireNonNull(svc, "Service interface cannot be null");
loader = (cl == null) ? ClassLoader.getSystemClassLoader() : cl;
AccessController.getContext() : null;
reload();
}
可以看到最終會(huì)創(chuàng)建一個(gè)LazyIterator迭代器帖蔓,這里使用了Lazy load矮瘟,我們用到的時(shí)候才會(huì)去load這個(gè)Class。
對(duì)于迭代器我們需要關(guān)心兩個(gè)方法塑娇,hasNext和next方法澈侠,而這兩個(gè)方法則直接調(diào)用了hasNextService和nextService方法。
private static final String PREFIX = "META-INF/services/";
Iterator<String> pending = null;
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;
}
可以看到埋酬,這里的邏輯就是讀取指定接口(key 文件) 的 實(shí)現(xiàn)列表(value 文件內(nèi)容)哨啃。
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,
// Android-changed: Let the ServiceConfigurationError have a cause.
"Provider " + cn + " not found", x);
// "Provider " + cn + " not found");
}
if (!service.isAssignableFrom(c)) {
// Android-changed: Let the ServiceConfigurationError have a cause.
ClassCastException cce = new ClassCastException(
service.getCanonicalName() + " is not assignable from " + c.getCanonicalName());
fail(service,
"Provider " + cn + " not a subtype", cce);
// 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
}
這里則是load 具體的實(shí)現(xiàn)類,然后保存到providers中写妥。
所以本質(zhì)上就是通過(guò)注解生成接口與實(shí)現(xiàn)的信息(也可以手動(dòng)寫拳球,只是AutoService幫我們做了而已),然后運(yùn)行時(shí)通過(guò)這部分信息來(lái)獲取具體的實(shí)現(xiàn)類珍特。
@AutoService
上面的demo簡(jiǎn)單實(shí)現(xiàn)了一下SPI的開發(fā)模式祝峻。而其中使用了@AutoService進(jìn)行了接口與實(shí)現(xiàn)的聲明,接下來(lái)我們來(lái)看看AutoService如何生成這部分映射關(guān)系的次坡。
@Documented
@Retention(SOURCE)
@Target(TYPE)
public @interface AutoService {
/** Returns the interfaces implemented by this service provider. */
Class<?>[] value();
}
可以看到AutoService也是一個(gè)注解呼猪。其主要的實(shí)現(xiàn)邏輯在AutoServiceProcessor中,他也是一個(gè)注解處理器砸琅。
我們看一下process方法:
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
try {
return processImpl(annotations, roundEnv);
} catch (Exception e) {
// We don't allow exceptions of any kind to propagate to the compiler
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
fatalError(writer.toString());
return true;
}
}
主要是調(diào)用了processImpl方法
private boolean processImpl(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
generateConfigFiles();
} else {
processAnnotations(annotations, roundEnv);
}
return true;
}
這里則是判斷這個(gè)環(huán)是否已經(jīng)完成了,而這個(gè)是否完成了的指標(biāo)會(huì)根據(jù)多個(gè)AnnotationProcessor的process結(jié)果來(lái)衡量轴踱,如果APT過(guò)程中生成的類也需要進(jìn)行注解處理的話則需要返回false症脂,方便再一次執(zhí)行。如果生成的類不需要進(jìn)行注解處理的話淫僻,那么則可以返回true诱篷。這里因?yàn)樯傻亩际俏募?nèi)容,不包含需要再次處理的類文件雳灵,所以一趟就可以搞定棕所。
如果還沒(méi)有完成則processAnnotations
private void processAnnotations(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(AutoService.class);
for (Element e : elements) {
TypeElement providerImplementer = (TypeElement) e;
AnnotationMirror annotationMirror = getAnnotationMirror(e, AutoService.class).get();
Set<DeclaredType> providerInterfaces = getValueFieldOfClasses(annotationMirror);
if (providerInterfaces.isEmpty()) {
error(MISSING_SERVICES_ERROR, e, annotationMirror);
continue;
}
for (DeclaredType providerInterface : providerInterfaces) {
TypeElement providerType = MoreTypes.asTypeElement(providerInterface);
if (checkImplementer(providerImplementer, providerType)) {
providers.put(getBinaryName(providerType), getBinaryName(providerImplementer));
} else {
String message = "ServiceProviders must implement their service provider interface. "
+ providerImplementer.getQualifiedName() + " does not implement "
+ providerType.getQualifiedName();
error(message, e, annotationMirror);
}
}
}
}
可以看到這里把AutoService注解修飾的類作為key,把注解的value值作為value悯辙。這樣子value就可以存在重復(fù)的情況了琳省。如果是反過(guò)來(lái)的話則需要保存為key - list的形式迎吵。
private void generateConfigFiles() {
Filer filer = processingEnv.getFiler();
for (String providerInterface : providers.keySet()) {
String resourceFile = "META-INF/services/" + providerInterface;
try {
SortedSet<String> allServices = Sets.newTreeSet();
try {
FileObject existingFile = filer.getResource(StandardLocation.CLASS_OUTPUT, "",
resourceFile);
Set<String> oldServices = ServicesFiles.readServiceFile(existingFile.openInputStream());
allServices.addAll(oldServices);
} catch (IOException e) {
log("Resource file did not already exist.");
}
Set<String> newServices = new HashSet<String>(providers.get(providerInterface));
if (allServices.containsAll(newServices)) {
log("No new service entries being added.");
return;
}
allServices.addAll(newServices);
log("New service file contents: " + allServices);
FileObject fileObject = filer.createResource(StandardLocation.CLASS_OUTPUT, "",
resourceFile);
OutputStream out = fileObject.openOutputStream();
ServicesFiles.writeServiceFile(allServices, out);
out.close();
log("Wrote to: " + fileObject.toUri());
} catch (IOException e) {
fatalError("Unable to create " + resourceFile + ", " + e);
return;
}
}
}
全部處理ok了就調(diào)用generateConfigFiles方法,這里通過(guò)遍歷之前存的provider map针贬,value就是他們要寫入的文件名击费,然后將這些配置寫入到配置文件中區(qū),當(dāng)然還有考慮到了已有的數(shù)據(jù)情況桦他,對(duì)舊數(shù)據(jù)進(jìn)行了拷貝處理蔫巩。
總結(jié)
主要學(xué)習(xí)了SPI設(shè)計(jì)模式,對(duì)于高內(nèi)聚低耦合的可替代功能快压,可以考慮使用SPI模式圆仔,模塊的插拔式設(shè)計(jì)。另外也了解到了AutoService注解處理的基本邏輯蔫劣,它不僅僅可以用于APT荧缘,也有其他的用途。