SpringBoot中动态注册Bean的方式

测试环境,本文源码

  • Java:8
  • SpringBoot:2.5.14
  • 示例场景:动态注册ProxyServlet,间接实现类似于Nginx的反向代理功能

先理解如何实现动态注册 Bean

由于在 SpringBoot 中,先进行 Bean 的定义,再根据定义进行 Bean 的实例化,所以实现动态 Bean ,我们只需要动态注册 Bean 定义即可。

这就用到了 BeanDefinitionRegistryPostProcessorpostProcessBeanDefinitionRegistry 这个方法。

源码注释

Modify the application context's internal bean definition registry after its standard initialization. All regular bean definitions will have been loaded, but no beans will have been instantiated yet. This allows for adding further bean definitions before the next post-processing phase kicks in.

所有常规的Bean都已经定义但尚未实例化时,这时候,你可以再新增 Bean 定义

一、通用方式

先说一个小插曲,建议搭配源码食用。假如三个类,他们分别实现且只实现了以下三个接口

  • BeanDefinitionRegistryPostProcessor
  • ApplicationContextAware
  • EnvironmentAware

这时候,这三个 Bean 的默认加载顺序如下。

并且,这三个 Bean 的方法执行顺序也是跟加载顺序相同。

但是,如果 Bean 实现了一个比 ApplicationContextAware 或者 EnvironmentAware 更先加载的 Bean ,那么就会出现先执行 setApplicationContext 或者 setEnvironment 的方法,为啥嘞?

是因为在 Bean 初始化前,先判定有没有实现 Aware 接口,如果实现过了,那么就直接优先调用 Aware 中的方法。如图。

既然明白了这个流程,那我们就可以实现功能了。

该通用方式是适用于 SpringBoot 框架中通用动态注册 Bean 的做法。主要是通过 BeanDefinitionRegistryPostProcessor 动态注册 Bean 定义。

java 复制代码
import org.mitre.dsmiley.httpproxy.ProxyServlet;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.HashMap;
import java.util.Map;

/**
 * 动态配置bean
 *
 * @author chenchuancheng
 * @since 2024/07/11 22:50
 */
@Configuration
public class DynamicBeanConfig implements BeanDefinitionRegistryPostProcessor, EnvironmentAware {

    private Environment environment;

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(ServletRegistrationBean.class);
        builder.addConstructorArgValue(new ProxyServlet());
        builder.addConstructorArgValue(environment.getProperty("proxy.servletUrl"));
        Map<String, String> initParams = new HashMap<>();
        initParams.put("targetUri", environment.getProperty("proxy.targetUrl"));
        initParams.put("log", "true");
        builder.addPropertyValue("initParameters", initParams);
        builder.addPropertyValue("name", environment.getProperty("proxy.name"));
        registry.registerBeanDefinition("proxyServlet", builder.getBeanDefinition());
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}

除了实现 Aware 接口,也可以通过构造函数注入,也可以保证调用方法时有值了。

二、特定方式

这个是使用 ServletContext 动态注册 Servlet 的方式。

java 复制代码
import org.mitre.dsmiley.httpproxy.ProxyServlet;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class ProxyServletInitializer implements ServletContextInitializer {

    private final Environment environment;

    public ProxyServletInitializer(Environment environment) {
        this.environment = environment;
    }

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        registerProxyServlet(servletContext,environment.getProperty("proxy.name"),environment.getProperty("proxy.targetUrl"));
    }

    private void registerProxyServlet(ServletContext servletContext, String name, String targetUri) {
        ProxyServlet proxyServlet = new ProxyServlet();
        ServletRegistration.Dynamic registration = servletContext.addServlet(name + "ProxyServlet", proxyServlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/" + name + "/*");
        
        Map<String, String> initParameters = new HashMap<>();
        initParameters.put("targetUri", targetUri);
        initParameters.put("log", "true");
        registration.setInitParameters(initParameters);
    }
}
相关推荐
Rust语言中文社区4 分钟前
【Rust日报】 CEL与Rust实现接近原生速度的解释执行
开发语言·后端·rust
武子康7 分钟前
大数据-247 离线数仓 - 电商分析 Hive 拉链表实战:订单历史状态增量刷新、闭链逻辑与错误排查
大数据·后端·apache hive
悟空码字7 分钟前
SpringBoot + 百度地图SDK,打造企业级位置服务中台
java·百度·地图·编程技术·后端开发
weixin199701080169 分钟前
网易考拉商品详情页前端性能优化实战
java·前端·python·性能优化
Natalia_Portman10 分钟前
springboot整合DolphinDB
java·数据库·spring boot·后端·db
hua8722214 分钟前
【Springboot3+vue3】从零到一搭建Springboot3+vue3前后端分离项目之后端环境搭建
java
不光头强15 分钟前
LinkedList知识点
java
beata18 分钟前
Spring Boot基础-1:用5分钟搭建第一个REST API应用(含深度原理解析)
spring boot
小码哥_常18 分钟前
JWT从入门到精通:一文解锁生成、验证与防篡改秘籍
后端