Here is an example of Java code that demonstrates the use of Service Provider Interface (SPI):\n\nFirst, let's create an interface called MessageService that defines a method sendMessage:\n\njava\npublic interface MessageService {\n void sendMessage(String message);\n}\n\n\nNext, let's create two implementations of the MessageService interface:\n\njava\npublic class EmailService implements MessageService {\n @Override\n public void sendMessage(String message) {\n System.out.println("Sending email: " + message);\n }\n}\n\npublic class SMSService implements MessageService {\n @Override\n public void sendMessage(String message) {\n System.out.println("Sending SMS: " + message);\n }\n}\n\n\nNow, let's create a file named META-INF/services/com.example.MessageService in the classpath with the fully qualified names of the implementations:\n\n\ncom.example.EmailService\ncom.example.SMSService\n\n\nFinally, let's create a class MessageSender that retrieves the implementations using the SPI and uses them to send messages:\n\njava\nimport java.util.ServiceLoader;\n\npublic class MessageSender {\n public static void main(String[] args) {\n ServiceLoader<MessageService> serviceLoader = ServiceLoader.load(MessageService.class);\n for (MessageService service : serviceLoader) {\n service.sendMessage("Hello, World!");\n }\n }\n}\n\n\nWhen you run the MessageSender class, it will load all the implementations of MessageService using the SPI and invoke the sendMessage method on each of them.\n\nNote: The META-INF/services/com.example.MessageService file should be in the classpath, and the fully qualified names of the implementations should be listed in separate lines.

Java SPI Example: Service Provider Interface Implementation

原文地址: https://www.cveoy.top/t/topic/pHbS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录