您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關使用Spring怎么動態注冊bean,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
I. 主動注冊Bean支持
借助BeanDefinition來實現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); } }
輸出如下
關于使用Spring怎么動態注冊bean就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。