欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

spring动态bean注册示例分享

程序员文章站 2023-11-13 18:31:04
1.在一些特殊的场景中需要动态向spring注册bean2.spring版本2.5.6 复制代码 代码如下:public class serviceserviceimpl...

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);
  }
 }
}