spi代码示例 java
时间: 2023-05-12 13:03:24 浏览: 98
以下是一个简单的 SPI 代码示例,使用 Java 编写:
1. 定义接口
public interface MyInterface {
void doSomething();
}
2. 实现接口
public class MyInterfaceImpl implements MyInterface {
@Override
public void doSomething() {
System.out.println("Doing something...");
}
}
3. 创建 SPI 配置文件
在 META-INF/services 目录下创建一个名为 com.example.MyInterface 的文件,内容为实现类的全限定名:
com.example.MyInterfaceImpl
4. 加载实现类
使用 ServiceLoader 类加载实现类:
ServiceLoader<MyInterface> loader = ServiceLoader.load(MyInterface.class);
for (MyInterface myInterface : loader) {
myInterface.doSomething();
}
这样就可以加载并调用实现类的方法了。
相关问题
java spi 代码
以下是一个简单的 Java SPI(Service Provider Interface)示例代码:
1. 创建接口:
```java
public interface MyService {
void doSomething();
}
```
2. 创建实现类:
```java
public class MyServiceImpl1 implements MyService {
@Override
public void doSomething() {
System.out.println("MyServiceImpl1 do something.");
}
}
public class MyServiceImpl2 implements MyService {
@Override
public void doSomething() {
System.out.println("MyServiceImpl2 do something.");
}
}
```
3. 在 META-INF/services 目录下创建一个文件,文件名为接口的全限定名,文件内容为实现类的全限定名:
```
com.example.MyService
com.example.MyServiceImpl1
com.example.MyServiceImpl2
```
4. 使用 Java SPI 加载实现类:
```java
public class Main {
public static void main(String[] args) {
ServiceLoader<MyService> loader = ServiceLoader.load(MyService.class);
for (MyService service : loader) {
service.doSomething();
}
}
}
```
5. 运行程序,输出如下:
```
MyServiceImpl1 do something.
MyServiceImpl2 do something.
```
写一段java的spi机制代码
好的,以下是Java SPI机制的示例代码:
1. 定义接口
```java
package com.example.spi;
public interface HelloService {
void sayHello();
}
```
2. 实现接口
```java
package com.example.spi.impl;
import com.example.spi.HelloService;
public class HelloServiceImpl implements HelloService {
@Override
public void sayHello() {
System.out.println("Hello, I'm HelloServiceImpl!");
}
}
```
3. 创建配置文件
在`src/main/resources/META-INF/services`目录下创建名为`com.example.spi.HelloService`的文件,文件内容为实现类的全限定类名,如下所示:
```
com.example.spi.impl.HelloServiceImpl
```
4. 加载实现类
```java
package com.example.spi;
import java.util.ServiceLoader;
public class Main {
public static void main(String[] args) {
ServiceLoader<HelloService> loader = ServiceLoader.load(HelloService.class);
for (HelloService helloService : loader) {
helloService.sayHello();
}
}
}
```
5. 运行结果
```
Hello, I'm HelloServiceImpl!
```