1. dynamically register beans with spring in some special scenarios
2. spring version 2.5.6
Copy codeThe Code is as follows:
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 register bean with spring container
* @ 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 search for class by class Name
* @ 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 );
}
}
}