Java SPI mechanism

Source: Internet
Author: User
Tags sin

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.