Spring Boot SPI实现

96 阅读1分钟

可先查看Java SPI

Spring Boot 的 SPI 机制主要依赖于spring.factories文件,该文件用于声明需要在特定条件下自动加载的类。这些类通常是 Spring Boot 的自动配置类、环境后处理器、监听器等。

一、实现Spring Boot SPI 的步骤
  1. 定义自动配置类
package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyAutoConfiguration {

    @Bean
    public MyService myService() {
        return new MyService();
    }
}
  1. 定义环境后处理器(EnvironmentPostProcessor)

    用于在Spring 应用启动期间自定义和修改环境属性

package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyAutoConfiguration {

    @Bean
    public MyService myService() {
        return new MyService();
    }
}
  1. 定义应用监听器(ApplicationListener)

    ApplicationListener接口的 onApplicationEvent 方法将在指定事件发生时被调用,以执行特定的业务逻辑(一般就记录日志)

package com.example.listener;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.out.println("Application context refreshed!");
    }
}
  1. 配置 spring.factories 文件

    在 META-INF/spring.factories 文件中添加以下内容:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.config.MyAutoConfiguration

org.springframework.boot.env.EnvironmentPostProcessor=\
com.example.env.MyEnvironmentPostProcessor

org.springframework.context.ApplicationListener=\
com.example.listener.MyApplicationListener
二、常见的 Spring Boot SPI 用例
  1. 自动配置(EnableAutoConfiguration)

    只要是实现一个starter,基本都要实现这个

    自动配置是 Spring Boot 的核心特性之一,它通过 spring.factories 文件加载所有的自动配置类,并根据当前环境条件来决定是否激活这些配置。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.config.MyAutoConfiguration

MyAutoConfiguration 类通常是一个使用 @Configuration 注解的类,包含一系列 @Bean 定义。

  1. 环境后处理器(EnvironmentPostProcessor)

    用来在应用上下文刷新之前修改环境属性,可添加自定义的属性

org.springframework.boot.env.EnvironmentPostProcessor=\
com.example.env.MyEnvironmentPostProcessor

MyEnvironmentPostProcessor 实现 EnvironmentPostProcessor 接口,并实现其 postProcessEnvironment 方法。

  1. 应用监听器

    在特定的应用事件发生时执行自定义逻辑,如应用启动、停止事件

org.springframework.context.ApplicationListener=\
com.example.listener.MyApplicationListener

MyApplicationListener 实现 ApplicationListener 接口,并重写 onApplicationEvent 方法。