gpt4 book ai didi

java - 以编程方式添加 AnnotationSessionFactoryBean

转载 作者:行者123 更新时间:2023-12-01 15:58:25 24 4
gpt4 key购买 nike

我有一个实现 BeanDefinitionRegistryPostProcessor 的类。

我正在尝试将 AnnotationSessionFactoryBean 添加到 postProcessBeanFactory 或 postProcessBeanDefinitionRegistry 中的 Spring 上下文中。我需要以编程方式执行此操作,以便可以在运行时配置该对象。

我正在尝试做:

@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);
<小时/>

--更新了解决方案:

必须做:

    GenericBeanDefinition bd = new GenericBeanDefinition();
bd.setBeanClass(AnnotationSessionFactoryBean.class);
bd.getPropertyValues().add("dataSource", dataSource);
bdr.registerBeanDefinition("sessionFactory", bd);

最佳答案

bean 定义不是实际的 bean,因此您无法进行强制转换。

使用 GenericBeanDefinition 而不是 RootBeanDefinition。然后,您可以使用 bean 定义的 propertyValues 为 AnnotationSessionFactoryBean 设置所需的 bean。

这样,您可以在调用registerBeanDefinition()之前执行如下操作:

bd.getPropertyValues().add("dataSource", dataSource);
bd.getPropertyValues().add("annotatedClasses", listOfClasses);
etc...

请注意,如果您遇到尚未定义 dataSource 或其他属性的问题,您可以使用 RuntimeBeanReference 作为占位符,方法是执行 bd.getPropertyValues().add 之类的操作(“dataSource”,new RuntimeBeanReference(“dataSource”)

关于java - 以编程方式添加 AnnotationSessionFactoryBean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4543023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com