spring动态bean注册示例分享
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);
}
}
}