1.在一些特殊的场景中需要动态向spring注册bean
2.spring版本2.5.6

复制代码 代码如下:
public class ServiceServiceImpl implements ServiceService, ApplicationContextAware {

 @Override
 public void setApplicationContext(org.springframework.context.ApplicationContext applicationContext)
   throws BeansException {
  this.context = applicationContext;
 }

 public void addBeanService(Service service) throws BVSException {
  if (!context.containsBean(service.getServiceName())) {
   Class<?> serviceClass = getServiceClass(service.getClassName());
   BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(serviceClass);
   beanDefinitionBuilder.addPropertyValue("servicename", service.getServiceName());
   registerBean(service.getServiceName(), beanDefinitionBuilder.getRawBeanDefinition());
  }

 }

 /**
  * @desc 向spring容器注册bean
  * @param beanName
  * @param beanDefinition
  */
 private void registerBean(String beanName, BeanDefinition beanDefinition) {
  ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) context;
  BeanDefinitionRegistry beanDefinitonRegistry = (BeanDefinitionRegistry) configurableApplicationContext
    .getBeanFactory();
  beanDefinitonRegistry.registerBeanDefinition(beanName, beanDefinition);
 }

 /**
  * @desc 根据类名查找class
  * @param className
  * @return
  * @throws BVSException
  */
 private Class<?> getServiceClass(String className) throws BVSException {
  try {
   return Thread.currentThread().getContextClassLoader().loadClass(className);
  } catch (ClassNotFoundException e) {
   log.error("not found service class:" + className, e);
   throw new BVSException("not found service class:" + className, e);
  }
 }
}

标签:
spring,动态bean

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
桃源资源网 Design By www.nqtax.com

评论“spring动态bean注册示例分享”

暂无“spring动态bean注册示例分享”评论...