springboot使用ImportBeanDefinitionRegistrar 动态注册bean
生活随笔
收集整理的這篇文章主要介紹了
springboot使用ImportBeanDefinitionRegistrar 动态注册bean
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【README】
1.采用? ImportBeanDefinitionRegistrar 動態注冊bean,應用場景有:
如 一個后端服務需要用到多個 rabbitmq集群客戶端,kafka客戶端;這時就需要手動注冊多個同類型的bean,但不同beanName,并用 @Resource(name="beanName") (或@Autowire+@Qualifier)來引入bean;
2.在封裝后臺框架時,經常會注冊同類型的多個bean,因此 ImportBeanDefinitionRegistrar 特別有用;
3.本文代碼轉自
https://www.logicbig.com/tutorials/spring-framework/spring-core/import-bean-registrar.htmlhttps://www.logicbig.com/tutorials/spring-framework/spring-core/import-bean-registrar.html
【例】使用 ImportBeanDefinitionRegistrar 動態注冊bean
public class MyBeanRegistrar implements ImportBeanDefinitionRegistrar {@Overridepublic void registerBeanDefinitions (AnnotationMetadata importingClassMetadata,BeanDefinitionRegistry registry) {GenericBeanDefinition gbd = new GenericBeanDefinition();gbd.setBeanClass(AppBean.class);// 顯然,這里是基于反射調用bean的setter方法 gbd.getPropertyValues().addPropertyValue("str", "value set from registrar");registry.registerBeanDefinition("appBean", gbd);} }自動裝配類
@Configuration @Import(MyBeanRegistrar.class) public class MyConfig {@BeanClientBean clientBean () {return new ClientBean();} }使用動態注冊的bean, AppBean
public class ClientBean {@Autowiredprivate AppBean appBean;public void doSomething () {appBean.process();} }AppBean 定義:
public class AppBean {private String str;public void setStr (String str) {this.str = str;}public void process () {System.out.println(str);} }測試方法入口:
public class ImportBeanDefinitionRegistrarExample {public static void main (String[] args) {ApplicationContext context =new AnnotationConfigApplicationContext(MyConfig.class);ClientBean bean = context.getBean(ClientBean.class);bean.doSomething();} }打印日志:
value set from registrar總結
以上是生活随笔為你收集整理的springboot使用ImportBeanDefinitionRegistrar 动态注册bean的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小米、OPPO、华为平板全面对比,谁才是
- 下一篇: MacBook电脑一键切换输入法MacB