Service Provider Interfaces Services provides discovery, dynamic replacement of discovery mechanisms
Example:
An interface:
Public Interface Calc {
Logger Logger = Loggerfactory.getlogger (Calc.class);
Object Calc (int calctype);
}
Two implementations:
To calculate the sin value:
Public class Implements Calc {
@Override
Public Object Calc (int calctype) {
Object value = Math.sin (Calctype);
Logger.info ("sin Result: {}", value);
return value;
}
}
Calculate the root:
Public class Implements Calc {
@Override
Public Object Calc (int calctype) {
Object value = math.sqrt (Calctype);
Logger.info ("sqrt result: {}", value);
return value;
}
}
A Service load class:
@Component
Public class Spiservice {
Public Object execcalc (int value) {
serviceloader<calc> loader = serviceloader.load (Calc.class);
iterator<calc> Iterator = Loader.iterator ();
while (Iterator.hasnext ()) {
return Iterator.next (). Calc (value);
}
return null;
}
Public Static void Main (string[] args) {
New Spiservice (). Execcalc (100);
}
}
A configuration file: classpath:meta-inf/services/xxx.xxx.Calc
Content: Feature classes that need to be loaded
such as:Xxx.xxx.SqrtCalc
The service load class executes, and the output calculates the root.
sample Application project: https://github.com/windwant/spring-boot-test
Official documents: https://docs.oracle.com/javase/tutorial/sound/SPI-intro.html
Java SPI mechanism