Service
经典的运行时服务加载, 常见于图像处理, 数据编码中.
经典使用
Service 的使用一般分为:
声明 Service
1 2 3 4 5 6 7 8 9
| package com.pancc.up.simple.spi;
public interface BackupService { boolean backup(Object[] data); }
|
实现一个接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| package com.pancc.up.simple.spi;
import lombok.extern.slf4j.Slf4j;
import java.util.Arrays;
@Slf4j public class BackupServiceLogImpl implements BackupService { @Override public boolean backup(Object[] data) { log.info("backup data: {}", Arrays.toString(data)); return true; } }
|
配置元文件
在 classpath 下新增一个文件: META-INF/services/com.pancc.up.simple.spi.BackupService
, 内容为 com.pancc.up.simple.spi.BackupServiceLogImpl
调用接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| package com.pancc.up.simple.spi;
import java.util.ServiceLoader;
public class BackupPiPes { public static void main(String[] args) { ServiceLoader<BackupService> services = ServiceLoader.load(BackupService.class); BackupService backupService = services.findFirst().orElseThrow(IllegalStateException::new); backupService.backup(new Object[]{1, 2, 3, 4}); } }
|