实现整个过程需要三个部分,第一就是根接口,第二是插件,第三是应用程序。这是3个java项目。
首先要下载jar包,百度搜索maven repository,然后搜索pf4j,如下图,下载第一个的相应版本就可以,我用的是1.2
然后,创建根节点项目,
package com.wgn.test1; import ro.fortsoft.pf4j.ExtensionPoint; /* * 根接口,继承ExtensionPoint * 将该项目打成jar包,放到plugin项目的lib文件夹下,然后构建配置路径 */ public interface Testpf4j extends ExtensionPoint { public void hello(); }
第三,创建插件项目,并将根接口项目打成jar包,放到插件项目的lib目录下,构建路径
package com.wgn.test2; import com.wgn.test1.Testpf4j; import ro.fortsoft.pf4j.Extension; import ro.fortsoft.pf4j.Plugin; import ro.fortsoft.pf4j.PluginWrapper; public class Testpf4jImpl extends Plugin { public Testpf4jImpl(PluginWrapper wrapper) { super(wrapper); } @Override public void start() { System.out.println("----------------------start"); } @Override public void stop() { System.out.println("----------------------stop"); } /* * 必须添加static修饰符 */ @Extension public static class Testpf4jImpls implements Testpf4j { @Override public void hello() { System.out.println("hello world!"); } } }
MANIFEST.MF:
Manifest-Version: 1.0 Plugin_Dependencies: Implementation-Title: Demo Plugin #2 Implementation-Version: 1.2.0 Archiver-Version: Plexus Archiver Built-By: root Specification_Title: Demo Plugin #2 Implementation-Vendor-Id: com.wgn.test1.Testpf4j Plugin-Version: 0.0.1 Plugin-Id: plugin01 Plugin-Provider: Decebal Suiu Plugin-Class: com.wgn.test2.TestPf4jImpl Build-dk: 1.8.0_102 Specification-Version; 1.2.0
extensions.idx:
com.wgn.test2.Testpf4jImpl$Testpf4jImpls
最后,新建程序项目,将插件放入plugins目录下,根接口放入lib目录下
package com.wgn.test2; import com.wgn.test1.Testpf4j; import ro.fortsoft.pf4j.Extension; import ro.fortsoft.pf4j.Plugin; import ro.fortsoft.pf4j.PluginWrapper; public class Testpf4jImpl extends Plugin { public Testpf4jImpl(PluginWrapper wrapper) { super(wrapper); } @Override public void start() { System.out.println("----------------------start"); } @Override public void stop() { System.out.println("----------------------stop"); } /* * 必须添加static修饰符 */ @Extension public static class Testpf4jImpls implements Testpf4j { @Override public void hello() { System.out.println("hello world!"); } } }