1. Concept
JDK’s built-in service discovery mechanism. SPI is a dynamic replacement and discovery mechanism. For example, there is an interface. If you want to add it dynamically at runtime, you just need to add an implementation. We often encounter the java.sql.Driver interface, and different vendors can implement different implementations of the same interface. mysql and postgresql provide different implementations for users, and Java's SPI mechanism can find services for a certain interface.
2. Example
public class KryoSerializer implements ObjectSerializer { @Override public byte[] serialize(Object obj) throws ObjectSerializerException { byte[] bytes; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { //获取kryo对象 Kryo kryo = new Kryo(); Output output = new Output(outputStream); kryo.writeObject(output, obj); bytes = output.toBytes(); output.flush(); } catch (Exception ex) { throw new ObjectSerializerException("kryo serialize error" + ex.getMessage()); } finally { try { outputStream.flush(); outputStream.close(); } catch (IOException e) { } } return bytes; } @Override public <T> T deSerialize(byte[] param, Class<T> clazz) throws ObjectSerializerException { T object; try (ByteArrayInputStream inputStream = new ByteArrayInputStream(param)) { Kryo kryo = new Kryo(); Input input = new Input(inputStream); object = kryo.readObject(input, clazz); input.close(); } catch (Exception e) { throw new ObjectSerializerException("kryo deSerialize error" + e.getMessage()); } return object; } @Override public String getSchemeName() { return "kryoSerializer"; } }
The above is the detailed content of What is SPI in Java?. For more information, please follow other related articles on the PHP Chinese website!