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);
    }
}
相关推荐
HerayChen3 小时前
HbuilderX 内存溢出报错
java·大数据·linux
程序员小白条3 小时前
0经验如何找实习?
java·开发语言·数据结构·数据库·链表
小马爱打代码4 小时前
Spring AI:搭建自定义 MCP Server:获取 QQ 信息
java·人工智能·spring
郭涤生4 小时前
QT 架构笔记
java·数据库·系统架构
韩立学长4 小时前
基于Springboot流浪动物领养网站0kh2iyb4(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·后端
daidaidaiyu4 小时前
基于LangGraph开发复杂智能体学习一则
java·ai
Moment4 小时前
从美团全栈化看 AI 冲击:前端转全栈,是自救还是必然 🤔🤔🤔
前端·后端·面试
小小8程序员4 小时前
STL 库(C++ Standard Template Library)全面介绍
java·开发语言·c++
a努力。5 小时前
Redis Java 开发系列#2 数据结构
java·数据结构·redis
a努力。5 小时前
腾讯Java面试被问:String、StringBuffer、StringBuilder区别
java·开发语言·后端·面试·职场和发展·架构