|
1.在一些特殊的場景中需要動態(tài)向spring注冊bean
2.spring版本2.5.6
復(fù)制代碼 代碼如下:
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 根據(jù)類名查找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);
}
}
}
jsp技術(shù):spring動態(tài)bean注冊示例分享,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請第一時間聯(lián)系我們修改或刪除,多謝。