I have a class that implements BeanDefinitionRegistryPostProcessor.
I am trying to add an AnnotationSessionFactoryBean to my Spring Context in either postProcessBeanFactory or postProcessBeanDefinitionRegistry. I need to do this programmatically so that I can configure the object at runtime.
I am trying to do:
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry bdr) throws BeansException {
RootBeanDefinition bd = new RootBeanDefinition(
AnnotationSessionFactoryBean.class);
// fails here.. can not cast
AnnotationSessionFactoryBean asfb = (AnnotationSessionFactoryBean)bd;
bdr.registerBeanDefinition("sessionFactory", asfb);
–updated with solution:
had to do a:
GenericBeanDefinition bd = new GenericBeanDefinition();
bd.setBeanClass(AnnotationSessionFactoryBean.class);
bd.getPropertyValues().add("dataSource", dataSource);
bdr.registerBeanDefinition("sessionFactory", bd);
The bean definition is not the actual bean, so you can’t cast.
Use GenericBeanDefinition instead of RootBeanDefinition. Then you can use the
propertyValuesof the bean definition to set the required beans for AnnotationSessionFactoryBean.This way, you can do something like the following before the calling registerBeanDefinition():
Note that if you run into issues where dataSource or other properties are not yet defined, you can use a
RuntimeBeanReferenceinstead as a placeholder by doing something likebd.getPropertyValues().add("dataSource", new RuntimeBeanReference("dataSource").