Java SPI机制

Service Provider Interfaces:服务提供发现,动态替换发现的机制

示例:

一个接口:

public interface Calc {
    Logger logger = LoggerFactory.getLogger(Calc.class);

    Object calc(int calcType);
}

两个实现:

计算sin值:

public class SinCalc implements Calc {
    @Override
    public Object calc(int calcType) {
        Object value = Math.sin(calcType);
        logger.info("sin result: {}", value);
        return value;
    }
}
计算开方:
public class SqrtCalc implements Calc {
    @Override
    public Object calc(int calcType) {
        Object value = Math.sqrt(calcType);
        logger.info("sqrt result: {}", value);
        return value;
    }
}

一个服务加载类:

@Component
public class SpiService {

    public Object execCalc(int value){
        ServiceLoader<Calc> loader = ServiceLoader.load(Calc.class);
        Iterator<Calc> iterator = loader.iterator();
        while (iterator.hasNext()) {
            return iterator.next().calc(value);
        }
        return null;
    }

    public static void main(String[] args) {
        new SpiService().execCalc(100);
    }
}

一个配置文件

classpath:META-INF/services/xxx.xxx.Calc

内容:需要加载的功能类

如:xxx.xxx.SqrtCalc

#org.windwant.spring.core.spi.service.SinCalc
org.windwant.spring.core.spi.service.SqrtCalc
#org.windwant.spring.core.spi.service.LogCalc

则 运行服务加载类执行,输出计算开方。

 

示例应用项目:https://github.com/windwant/spring-dubbo-service

官方文档:https://docs.oracle.com/javase/tutorial/sound/SPI-intro.html

 

posted @ 2018-01-24 17:35  WindWant  阅读(417)  评论(0编辑  收藏  举报
文章精选列表