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);
}
}
}
上一篇: Python_正则表达式
推荐阅读
-
spring动态bean注册示例分享
-
Spring Bean注册解析(一)
-
深入理解 Spring @Import 不同方式注册Bean
-
品Spring:SpringBoot轻松取胜bean定义注册的“第一阶段”
-
Nacos--在Spring cloud中使用Spring Cloud Alibaba Nacos Discovery(服务注册+配置管理示例)
-
动态设定Spring中bean的属性
-
动态设定Spring中bean的属性
-
JSP 开发之Spring Boot 动态创建Bean
-
Spring注解开发——2、组件注册[email protected]&@Bean给容器中注册组件
-
Spring注解开发——7、组件注册[email protected]按照条件注册bean