Solon2 开发之插件,一、插件

Solon Plugin 是框架的核心接口,简称“插件”。其本质是一个“生命周期”接口。它可让一个组件类参与程序的生命周期过程(这块看下:《应用启动过程与完整生命周期》):

@FunctionalInterface
public interface Plugin {
    //启动
    void start(AopContext context) throws Throwable;
    //预停止
    default void prestop() throws Throwable{}
    //停止
    default void stop() throws Throwable{}
}

目前对它的使用主要有两种方式:

1、做为具有生命周期的组件使用

做为注解组件,实例产生后会加入 SolonApp 实例的 plugins 列表,并会执行 start 接口,当程序停止时会触发 stop 接口。

这个方式,一般是需要对一些有生命周期的对象进行管理,比如通讯服务:

@Component
public class StompServerPlugin implements Plugin {
    @Inject("${server.stopm.port}")
    int port;
    
    StompServer server;
    
    @Override
    public void start(AopContext context) throws Throwable {
        server = new StompServer(port);
        server.start();
    }

    @Override
    public void stop() throws Throwable {
        server.stop();
    }
}

目前,这个方式较少使用(有大量的通讯服务或有生命周期对象已被封装成插件)。如无必要,也不建议使用。

2、做为一个模块生命周期的对接使用,为框架或业务提供扩展能力

生态体系里的所有插件的封装,都基于这个方式。也是最常使用的场景。

  • 在这个方式里,不能使用注解能力(为了绝对的安全)
  • 且需要使用配置文件申明插件(为了获得更早的执行时机)
public class XPluginImpl implements Plugin {
    @Override
    public void start(AopContext context) throws Throwable {
        //...
    }

    @Override
    public void stop() throws Throwable {
        
    }
}

具体看一下《插件扩展机制(Spi)》

posted @ 2023-02-13 22:13  带刺的坐椅  阅读(45)  评论(0编辑  收藏  举报