程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> JSP編程 >> 關於JSP >> spring動態bean注冊示例分享

spring動態bean注冊示例分享

編輯:關於JSP

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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved