将自定义bean添加到Spring上下文 [英] Add custom beans to Spring context

查看:1119
本文介绍了将自定义bean添加到Spring上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些带有自定义注释的类,它们不应该被实例化(抽象类,它只是真正的bean的子组件)。但是在这些类之上,在运行时,在上下文初始化阶段,我想把额外的bean放到应用程序上下文中。

I have some classes, with a custom annotation, that shouldn't be instantiated (abstract class, and it's just a subcomponents for a real beans). But on top of this classes, on runtime, on context initialization phase, I want to put extra beans into application context.

所以,基本上我需要扫描类路径,进程结果,并将新bean引入当前的应用程序上下文。

So, basically I need to scan classpath, process results, and introduce new beans into curent application context.

似乎spring-mvc,spring-tasks和spring-integration正在这样做(我试图从中学习它来源 - 没有运气)

It seems that spring-mvc, spring-tasks and spring-integration are doing this (I tried to learn it from sources - no luck)

我发现我可以创建自己的 BeanFactoryPostProcessor ,扫描类路径并调用<$ c我的自定义bean的$ c> registerSingleton 。但我不确定这是引入新bean的好方法(似乎它只用于exce beans bean的后期处理)。我相信有一些Spring内部工具可以重复使用以简化流程。

I found that I can create my own BeanFactoryPostProcessor, scan classpath and call registerSingleton for my custom bean. But I'm not sure that it's a good way for introducing new beans (seems that it's used only for postprocess of exising beans only). And I believe there are some Spring internal tools that I may reuse to simplify process.

在Spring上下文初始化中引入额外Bean的传统方法是什么?

What is a conventional way to introduce extra beans on Spring context initialization?

推荐答案

您的观察实际上是正确的, BeanFactoryPostProcessor 是Spring提供修改bean定义/实例的机制的两种方式之一在将它们提供给应用程序之前(另一个是使用 BeanPostProcessors

Your observation is actually correct, BeanFactoryPostProcessor is one of the two ways Spring provides a mechanism to modify the bean definition/instances before making them available to the application(the other is using BeanPostProcessors)

你绝对可以使用BeanFactoryPostProcessors来添加/修改bean定义,这里是一个来自Spring Integration代码库的示例如果没有用户明确指定,则会添加errorChannel,您可以使用类似的代码来注册新的bean:

You can absolutely use BeanFactoryPostProcessors to add/modify bean definitions, here is one sample from Spring Integration codebase that adds a errorChannel if not explicitly specified by a user, you can probably use a similar code for registering your new beans:

    RootBeanDefinition errorChannelDef = new RootBeanDefinition();
    errorChannelDef.setBeanClassName(IntegrationNamespaceUtils.BASE_PACKAGE
            + ".channel.PublishSubscribeChannel");
    BeanDefinitionHolder errorChannelHolder = new BeanDefinitionHolder(errorChannelDef,
            IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME);
    BeanDefinitionReaderUtils.registerBeanDefinition(errorChannelHolder, registry);

这篇关于将自定义bean添加到Spring上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆