友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

75. ServiceLoader

1
2
3
4
5
6
7
8
9
package com.diguage.truman;

/**
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-04-08 10:47
 */
public interface ServiceLoaderSay {
    void say();
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package com.diguage.truman;

/**
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-04-08 10:48
 */
public class ServiceLoaderSayHello implements ServiceLoaderSay {
    @Override
    public void say() {
        System.out.println("Hello, https://www.diguage.com/");
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package com.diguage.truman;

/**
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-04-08 10:48
 */
public class ServiceLoaderSayGoodbye implements ServiceLoaderSay {
    @Override
    public void say() {
        System.out.println("Goodbye, https://www.diguage.com/");
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.diguage.truman;

import org.junit.jupiter.api.Test;

import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-04-08 10:40
 */
public class ServiceLoaderTest {
    @Test
    public void test() {
        ServiceLoader<ServiceLoaderSay> loader
                = ServiceLoader.load(ServiceLoaderSay.class);
        Iterator<ServiceLoaderSay> iterator = loader.iterator();
        while (iterator.hasNext()) {
            ServiceLoaderSay say = iterator.next();
            say.say();
        }
    }
}

经过测试,有几点需要注意:

  1. 只支持 public 的类。D瓜哥测试,这是因为内部需要创建对象,其他访问控制不能在 ServiceLoader 类中创建对象。

  2. 不支持 Outter.Inner 这样的内部类 ,即使是 public static class

75.1. 参考资料

  1. 浅析JDK中ServiceLoader的源码 - Throwable’s Blog — 这里的代码是基于 JDK 8 的,和 JDK 11 的代码已经相差很大。

  2. 剖析 SPI 在 Spring 中的应用 — 讲解了 Java、Spring、Dubbo 等三方面的实现,细致入微。

  3. SpringBoot的SPI机制