Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

java - Add custom beans to Spring context

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.

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

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

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...