Java SPI Mechanism Usage Demo

Source: Internet
Author: User

① Building a MAVEN project

Contains the following directory structure:

Src/main/java

Src/main/resources

Src/test/java

Src/test/resources

② creating a new Meta-inf/services directory under the Src/main/resources directory

③ Create a new package in Src/main/java, and then create a new interface

For example

Package Com.liu.spi;public interface IA {void print ();}

④ several new implementation classes

For example:

Aiaimpl.java

Package Com.liu.spi;public class Aiaimpl implements IA {public void print () {System.out.println ("AIA");}}

Biaimpl.java

Package Com.liu.spi;public class Biaimpl implements ia{public void print () {System.out.println ("BIA");}}

Ciaimpl.java

Package Com.liu.spi;public class Ciaimpl implements IA {public void print () {System.out.println ("CIA");}}

⑤ Create a new file in the Src/main/resources/meta-inf/services directory named Com.liu.spi.IA (the full class name of the interface)

The file content is: The full class name of the interface implementation class (Must wrap)

Com.liu.spi.AIAImpl
Com.liu.spi.BIAImpl
Com.liu.spi.CIAImpl

Note: For comments, use "#" before the full class name

⑥ Writing test class Iatest.java

The code is as follows:

Package Com.liu.spi;import Java.util.iterator;import Java.util.serviceloader;public class Iatest {public static void Main (string[] args) {serviceloader<ia> Spiloader = Serviceloader.load (ia.class);          iterator<ia> iaiterator = Spiloader.iterator ();          while (Iaiterator.hasnext ()) {              iaiterator.next (). print ();}}  

⑦ printing results are as follows:

Java SPI Mechanism Usage Demo

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.