In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
How to dynamically register beans in Spring, many novices are not very clear about this, in order to help you solve this problem, the following small series will explain in detail for everyone, people who have this need can learn, I hope you can gain something.
Why dynamic bean registration is needed
Most of the time, static configuration information can meet system requirements. However, in some scenarios, we need to dynamically generate beans based on information in static configuration, in which case we need to dynamically register bean functionality.
For example:
The user defines an interface as follows, and the implementation of the interface is generated by the framework without the user writing it himself. In this case, the implementation class needs to be dynamically registered in the container.
@Rest("http://localhost:8081/test")public interface IRequestDemo {@GETResultBean get1();@GET("/get2")ResultBean getWithKey(@Param("key") String key);@GET("/get3")ResultBean getWithMultKey(@Param("key1") String key, @Param("key2") String key2);}@componetpublic class test { @Autowired IRequestDemo demo; public String test() {String msg = "invoke remote rest result";ResultBean get1 = demo.get1();msg += "get1 result=" + get1;ResultBean get2 = demo.getWithKey("key-------");msg += "get2 result=" + get2;ResultBean get3 = demo.getWithMultKey("key11111", "key22222");msg += "get3 result=" + get3;return msg; }}
Code snippet from my colleague [Xiaofeng Qing][1] project [MyRestUtil][2]
API for dynamically registering beans
Bean definitions in Spring are stored in the **BeanDefinitionRegistry** interface, and instances of singleton beans are stored in the **SingletonBeanRegistry** interface.
Therefore, dynamic bean registration is divided into two ways:
1. void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException method using BeanDefinitionRegistry interface
2. void registerSingleton(String beanName, Object singletonObject) method using SingletonBeanRegistry interface
The difference is that with the former, the Spring container instantiates bean instances based on BeanDefinition, whereas with the latter, bean instances are objects passed to the registerSingleton method.
The DefaultListableBeanFactory interface implements both interfaces and is commonly used in practice.
Dynamic registration in normal beans
Dynamic registration can be done anywhere BeanDefinitionRegistry or SingletonBeanRegistry instances are obtained.
However, if the bean is not registered in BeanFactoryPostProcessor, then the bean cannot be processed by **BeanPostProcessor**, that is, aop, Bean Validation, etc. cannot be applied to it.
Dynamic registration in **BeanFactoryPostProcessor**
BeanFactory executes BeanFactoryPostProcessor immediately after loading the bean definition during the Spring container startup process. At this time, dynamically registering the bean ensures that the dynamically registered bean is processed by BeanPostProcessor and that its instantiation and initialization always precede the bean that depends on it.
example
Register at BeanFactoryPostProcessor
@Component@Slf4jpublic class PersonBeanFactoryPostProcessor implements BeanFactoryPostProcessor {@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {DefaultListableBeanFactory defaultListableBeanFactory= (DefaultListableBeanFactory) beanFactory;//Register Bean definition, container returns bean according to definition log.info ("register personManager1>>>>>>>>>>>>>>>> log.info("register personManager2>>>>>>>>>>>>>>>>");PersonDao personDao = beanFactory.getBean(PersonDao.class);PersonManager personManager = new PersonManager();personManager.setPersonDao(personDao);beanFactory.registerSingleton("personManager2", personManager);}}
Register in a normal bean
@RestController@Slf4jpublic class PersonManagerRegisterController {/** * The Application context. */@AutowiredGenericApplicationContext applicationContext;/** * The Bean factory. */@AutowiredConfigurableBeanFactory beanFactory;/** * Dynamic bean registration, where the bean registered does not have AOP support * curl http://localhost:8080/registerPersonManager */@GetMapping("/registerPersonManager")public void registerPersonManager() {PersonDao personDao = applicationContext.getBean(PersonDao.class);PersonManager personManager = new PersonManager();personManager.setPersonDao(personDao);beanFactory.registerSingleton("personManager3", personManager);}... ... Did reading the above help you? If you still want to have further understanding of related knowledge or read more related articles, please pay attention to the industry information channel, thank you for your support.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.