您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)使用Spring怎么動態(tài)注冊bean,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。
I. 主動注冊Bean支持
借助BeanDefinition來實現(xiàn)bean的定義,從最終的使用來看,代碼比較少,幾行而已
public <T> T registerBean(String name, Class<T> clazz, Object... args) { BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clazz); if (args.length > 0) { for (Object arg : args) { beanDefinitionBuilder.addConstructorArgValue(arg); } } BeanDefinition beanDefinition = beanDefinitionBuilder.getRawBeanDefinition(); BeanDefinitionRegistry beanFactory = (BeanDefinitionRegistry) applicationContext.getBeanFactory(); beanFactory.registerBeanDefinition(name, beanDefinition); return applicationContext.getBean(name, clazz); }
測試如下
import com.github.hui.story.quickstory.server.VisitService; import lombok.ToString; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.stereotype.Component; @Component public class BeanHolder { private final ConfigurableApplicationContext applicationContext; public BeanHolder(ConfigurableApplicationContext applicationContext) { this.applicationContext = applicationContext; initSer(); } public void initSer() { InrSer ser = registerBean("test", InrSer.class); ser.name = "一灰"; ser.uid = 22; System.out.println(ser); InrSer ser2 = registerBean("test2", InrSer.class, "一灰灰Blog", 20); System.out.println(ser2); } @ToString public static class InrSer { private String name; private Integer uid; @Autowired private VisitService visitService; public InrSer() { } public InrSer(String name, Integer uid) { this.name = name; this.uid = uid; } } private <T> T registerBean(String name, Class<T> clazz, Object... args) { BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clazz); if (args.length > 0) { for (Object arg : args) { beanDefinitionBuilder.addConstructorArgValue(arg); } } BeanDefinition beanDefinition = beanDefinitionBuilder.getRawBeanDefinition(); BeanDefinitionRegistry beanFactory = (BeanDefinitionRegistry) applicationContext.getBeanFactory(); beanFactory.registerBeanDefinition(name, beanDefinition); return applicationContext.getBean(name, clazz); } }
輸出如下
關(guān)于使用Spring怎么動態(tài)注冊bean就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。