Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to register Bean to Spring dynamically

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to dynamically register Bean to Spring related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe you will have something to gain after reading this article on how to dynamically register Bean to Spring, let's take a look.

1. Theory

Generally, if you want to register the class with the spring container and let spring instantiate it, the common methods are as follows:

Xml is configured through bean node

Use @ Service, @ Controller, @ Conponent, and so on.

Recently, when I was studying initialization through Spring, I scanned custom annotations and found that Bean was obtained by implementing BeanDefinitionRegistryPostProcessor, thus getting custom annotations.

Spring allows us to register the specified class with the spring container through code.

When the Spring container is initialized, the relevant definitions of bean are read from the resources and saved in BeanDefinitionMap. The operation of instantiating bean is based on the definition of these bean. Before instantiation, Spring allows us to change the definition of bean through custom extension. Once the definition changes, the following instance changes, and the beanFactory post processor, that is, BeanFactoryPostProcessor, is used to change the definition of bean.

The invokeBeanFactoryPostProcessors method is used to find all the beanFactory post-processors and call them to change the definition of the bean.

BeanDefinitionRegistryPostProcessor inherits the BeanFactoryPostProcessor interface, and the implementation class of BeanFactoryPostProcessor can control the definition of bean when its postProcessBeanFactory method is called, so the implementation class of BeanDefinitionRegistryPostProcessor needs to implement the following two methods:

Void postProcessBeanFactory (ConfigurableListableBeanFactory beanFactory) throws BeansException

In the implementation of this method, it is mainly used to change the definition of bean.

Void postProcessBeanDefinitionRegistry (BeanDefinitionRegistry registry) throws BeansException

This method is used to register more bean into the spring container, and observe the input parameter BeanDefinitionRegistry interface in detail to see what capabilities this parameter can bring us.

As can be seen from BeanDefinitionRegistry, BeanDefinitionRegistry provides a wealth of methods to operate BeanDefinition. Judgment, registration, removal and other methods are ready. When we write the content of the postProcessBeanDefinitionRegistry method, we can directly use these methods of the input parameter registry to complete judgment, registration, removal and other operations.

InvokeBeanFactoryPostProcessors (beanFactory) in org.springframework.context.support.AbstractApplicationContext#refresh

Used to find all the beanFactory post-processors and call them to change the definition of bean.

InvokeBeanFactoryPostProcessors (beanFactory) is actually a delegate

Org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors (beanFactory, getBeanFactoryPostProcessors ())

Method to deal with it.

First deal with the contents of the BeanFactoryPostProcessor:

The postProcessBeanDefinitionRegistry method of all bean that implements the BeanDefinitionRegistryPostProcessor interface will be called, and then its postProcessBeanFactory method will be called. In this way, if we customize the implementation class of the BeanDefinitionRegistryPostProcessor interface, the postProcessBeanDefinitionRegistry and postProcessBeanFactory methods we develop will be executed once.

Boolean reiterate = true;while (reiterate) {reiterate = false; / / find out all bean names that implement the BeanDefinitionRegistryPostProcessor interface postProcessorNames = beanFactory.getBeanNamesForType (BeanDefinitionRegistryPostProcessor.class, true, false) For (String ppName: postProcessorNames) {/ / in the previous logic, bean that implements both PriorityOrdered and Ordered has been processed, so through processedBeans filtering, those that are not in processedBeans will be processed here if (! processedBeans.contains (ppName)) {/ / get bean BeanDefinitionRegistryPostProcessor pp = beanFactory.getBean (ppName, BeanDefinitionRegistryPostProcessor.class) based on name and type / put all the bean that has called the postProcessBeanDefinitionRegistry method in the registryPostProcessors registryPostProcessors.add (pp); / / put all the names of the bean that have called the postProcessBeanDefinitionRegistry method in the processedBeans processedBeans.add (ppName); / / execute the postProcessBeanDefinitionRegistry method pp.postProcessBeanDefinitionRegistry (registry) of this bean / / change the condition to exit while reiterate = true;} / all bean,// that have executed postProcessBeanDefinitionRegistry methods are saved in registryPostProcessors. Now let's execute the postProcessBeanFactory methods invokeBeanFactoryPostProcessors (registryPostProcessors, beanFactory) of these bean. What is saved in / regularPostProcessors is the BeanFactoryPostProcessor implementation class brought by all the input parameters, and the implementation class of BeanDefinitionRegistryPostProcessor has been removed. Now let these bean execute postProcessBeanFactory method 2, the actual combat code public class AnnotationScannerConfigurer implements BeanDefinitionRegistryPostProcessor {@ Override public void postProcessBeanDefinitionRegistry (BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {/ / create an object of bean's definition class RootBeanDefinition rootBeanDefinition = new RootBeanDefinition (TestServiceImpl.class) / / Register the definition of Bean to the Spring environment beanDefinitionRegistry.registerBeanDefinition ("testService", rootBeanDefinition);} @ Override public void postProcessBeanFactory (ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {/ / bean is key, and the instance of bean is value Map beanMap = configurableListableBeanFactory.getBeansWithAnnotation (AutoDiscoverClass.class);}

In fact, in the process of actual use, when Spring starts up, it scans custom annotations through the postProcessBeanFactory method of BeanFactoryPostProcessor interface.

ConfigurableListableBeanFactory.getBeansWithAnnotation (AutoDiscoverClass.class)

Get each Bean with custom annotations.

This method does not meet my actual needs.

This is the end of the article on "how to dynamically register Bean to Spring". Thank you for reading! I believe that everyone has a certain understanding of "how to dynamically register Bean to Spring" knowledge, if you want to learn more knowledge, welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report