Examples of spring dynamic bean Registration

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.