Dynamically loading plugin jars using ServiceLoader

后端 未结 3 581
南笙
南笙 2020-12-02 07:12

I\'m trying to create a plugin system for my application, and I want to start with something simple. Every plugin should be packed in a .jar file and implement the Sim

相关标签:
3条回答
  • 2020-12-02 07:49

    Starting from Java 9 the service providing scanning will be much easier and efficient. No more need for META-INF/services.

    In the interface module declaration declare:

    uses com.foo.spi.Service;
    

    And in the provider's module:

    provides com.foo.spi.Service with com.bar.ServiceImplementation
    
    0 讨论(0)
  • 2020-12-02 07:54

    The problem was very simple. And stupid. In the plugin .jar files the /services/plugintest.SimplePlugin file was missing inside the META-INF directory, so the ServiceLoader couldn't identify the jars as services and load the class.

    That's pretty much all, the second (and cleaner) way works like a charm.

    0 讨论(0)
  • 2020-12-02 07:58

    The solution for your application concept has been already described in Oracle Documentation (including dynamically loading JARs)

    Creating Extensible Applications With the Java Platform http://www.oracle.com/technetwork/articles/javase/extensible-137159.html

    on the bottom of the article you will find links to

    • source code of the example
    • Javadoc ServiceLoader API

    In my opinion it is better to slightly modify Oracle's example than reinventing the wheel as Omer Schleifer said.

    0 讨论(0)
提交回复
热议问题