In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of "how to apply the SPI mechanism in Java". The editor shows you the operation process through an actual case, and the operation method is simple, fast and practical. I hope this article "how to apply the SPI mechanism in Java" can help you solve the problem.
I. Preface
The full name of SPI is Service Provider Interface, which literally means service provider interface. It is the interface provided by jdk to "service provider" or "plug-in developer".
In object-oriented design, we usually adopt interface-oriented programming between modules, but in the actual programming process, the implementation of API is encapsulated in jar. When we want to change the implementation method, we have to generate a new jar to replace the previous implementation class. It can be realized through the SPI mechanism of jdk. First of all, without modifying the original jar as an interface, the original jar can be replaced with another jar.
Summarize the idea of SPI: in each module of the system, there are often different implementation schemes, such as log module scheme, xml parsing scheme and so on. In order not to specify the implementation class when loading the module, we need a service discovery mechanism, and java spi provides such a mechanism. Somewhat similar to the idea of IoC, moving control of service assembly out of the program is especially important in modular design.
By the way, is the Java SPI mechanism used in many large middleware, such as Dubbo, which is an advanced necessary knowledge point for advanced Java development and must be mastered.
II. SPI specification
Define the general interface of the service, and provide specific implementation classes for the general service interface.
1. In the META-INF/services/ directory of the jar package (service provider), create a new file named "fully qualified name" of the SPI interface. The content of the file is the "fully qualified name" of the concrete implementation class of the interface
two。 Put the jar where spi is located in the classpath of the main program
3. Service callers use java.util.ServiceLoader to dynamically load specific implementation classes into JVM
Third, SPI application case 3.1 database driver
The spi implementation of java.sql.Driver, including mysql driver, oracle driver and so on. In mysql, for example, the implementation class is com.mysql.jdbc.Driver. In mysql-connector-java-5.1.6.jar, we can see that there is a META-INF/services directory with a file named java.sql.Driver, and the content is com.mysql.jdbc.Driver.
When we use JDBC to get a connection, we usually call the DriverManager.getConnection () method to get the connection object, and when the Driver class is initialized, we use ServiceLoader to dynamically obtain the driver implementation of "registration" under classpath:
Static {loadInitialDrivers (); println ("JDBC DriverManager initialized");} private static void loadInitialDrivers () {. AccessController.doPrivileged (new PrivilegedAction () {public Void run () {/ / use ServiceLoader to dynamically load the specific driver implementation class ServiceLoader loadedDrivers = ServiceLoader.load (Driver.class); Iterator driversIterator = loadedDrivers.iterator () Try {while (driversIterator.hasNext ()) {driversIterator.next ();}} catch (Throwable t) {/ / Do nothing} return null;}}) . } 3.2 Slf4j
Slf4j is a typical facade interface. We use log4j as the diary framework in the early morning. We need to introduce both slf4j and log4j dependencies. Later, logback is more popular, and we also want to switch the project to logback. At this time, using the mechanism of SPI, we just need to replace the jar package of log4j with the jar package of logback.
In log4j-to-slf4j.jar, we can see the SPI interface declaration of the service provider mentioned earlier:
So we only need to introduce log4j-to-slf4j.jar into classpath,slf4j to get org.apache.logging.slf4j.SLF4JProvider as the implementation class.
4. SPI example
Module dependencies:
4.1 spi-operate-service module
Define the INumOperate interface in spi-operate-service:
Package cn.bigcoder.spi.operate.service;/** * @ author: Jindong.Tian * @ date: 2020-11-29 * @ description: * * / public interface INumOperate {int exec (int num1, int num2);} 4.2 spi-operate-add module
Define the addition implementation in spi-operate-add:
Package cn.bigcoder.spi.operate.add;import cn.bigcoder.spi.operate.service.INumOperate;/** * @ author: Jindong.Tian * @ date: 2020-11-29 * @ description: * / public class NumAddOperateImpl implements INumOperate {public int exec (int num1, int num2) {return num1 + num2;}}
Create a cn.bigcoder.spi.operate.service.INumOperate file in the resource/METAINF/resoures directory:
Cn.bigcoder.spi.operate.add.NumAddOperateImpl4.3 spi-operate-multiplication module
Define the implementation of multiplication in the spi-operate-multiplication module:
Package cn.bigcoder.spi.operate.multiplication;import cn.bigcoder.spi.operate.service.INumOperate;/** * @ author: Jindong.Tian * @ date: 2020-11-29 * @ description: * / public class NumMultiOperateImpl implements INumOperate {public int exec (int num1, int num2) {return num1 * num2;}}
Similarly, create a cn.bigcoder.spi.operate.service.INumOperate file in the resource/METAINF/resoures directory:
Cn.bigcoder.spi.operate.multiplication.NumMultiOperateImpl4.4 spi-operate-consumer module
In the spi-operate-consumer module, we write a test class to get the INumOperate implementation class in classpath:
Package cn.bigcoder.spi.operate;import cn.bigcoder.spi.operate.service.INumOperate;import org.junit.Test;import java.util.Iterator;import java.util.ServiceLoader;/** * @ author: Jindong.Tian * @ date: 2020-11-29 * @ description: * * / public class INumOperateTest {@ Test public void test () {/ / SPI mechanism, find all the implementation classes, and execute ServiceLoader loader = ServiceLoader.load (INumOperate.class) sequentially. Iterator iterator = loader.iterator (); if (iterator.hasNext ()) {INumOperate numOperate = iterator.next (); System.out.println (numOperate.exec (1,2));} else {throw new RuntimeException ("cn.bigcoder.spi.operate.INumOperate implementation class not found in classpath");}
At this point, if we introduce spi-operate-add into spi-operate-consumer, the test method performs the sum operation; if spi-operate-multiplication is introduced, the test method performs the multiplication operation.
This is the end of the introduction on "how to apply the SPI mechanism in Java". Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.