如何在 Spring Boot 中动态注册 bean?

我希望在运行时覆盖 Spring 的 SSLContext。因此,我试图找到将以下方法动态注册为 bean 的方法。


对于前。调用 GetMapping 端点时,应将以下方法作为 bean 注入到 Spring IoC 中。


public static SSLContext getSSLContext() throws Exception {

    TrustManager[] trustManagers = new TrustManager[] {

            new ReloadableX509TrustManager(truststoreNewPath)

    };

    SSLContext sslContext = SSLContext.getInstance("SSL");

    sslContext.init(null, trustManagers, null);

    return sslContext;

}

我怎样才能做到这一点?


LEATH
浏览 150回答 3
3回答

手掌心

Spring 5提供了Bean注册,可以动态完成。Supplier<SSLContext> sslcontextSupplier = () -> getSSLContext(); context.registerBean("sslcontext",SSLContext.class,sslcontextSupplier);

SMILET

您可以使用 ConfigurableBeanFactory 在运行时手动注册 bean。@Servicepublic class RegisterBeansDynamically implements BeanFactoryAware {    private ConfigurableBeanFactory beanFactory;    public <T> void registerBean(String beanName, T bean) {        beanFactory.registerSingleton(beanName, bean);    }    @Override    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {        this.beanFactory = (ConfigurableBeanFactory) beanFactory;    }}但请记住:必须刷新您的上下文,使其他 bean 能够自动注入您的新 bean,否则它们必须从应用程序上下文动态访问它们。

开心每一天1111

这是演示。public class Demo implements ApplicationContextAware {&nbsp; &nbsp; private ApplicationContext applicationContext;&nbsp; &nbsp; @Override&nbsp; &nbsp; public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {&nbsp; &nbsp; &nbsp; &nbsp; this.applicationContext = applicationContext;&nbsp; &nbsp; &nbsp; &nbsp; ConfigurableApplicationContext context = (ConfigurableApplicationContext)applicationContext;&nbsp; &nbsp; &nbsp; &nbsp; DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory)context.getBeanFactory();&nbsp; &nbsp; &nbsp; &nbsp; BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(YourClass.class);&nbsp; &nbsp; &nbsp; &nbsp; beanDefinitionBuilder.addPropertyValue("property1", "propertyValue");&nbsp; &nbsp; &nbsp; &nbsp; beanDefinitionBuilder.addPropertyValue("property2", applicationContext.getBean(AnotherClass.class));&nbsp; &nbsp; &nbsp; &nbsp; beanFactory.registerBeanDefinition("yourBeanName", beanDefinitionBuilder.getBeanDefinition());&nbsp; &nbsp; }}您可以将寄存器部分移动到您的方法中(从 开始BeanDefinitionBuilder)。我想这会满足你的需求。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java