gpt4 book ai didi

java - ApplicationContext.getBean(Class clazz) 不适用于代理

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:45:57 25 4
gpt4 key购买 nike

我在 Spring 中有一个 bean 定义,它是代理对应物,可以在任何地方使用:

<bean name="my.Bean" class="org.springframework.aop.framework.ProxyFactoryBean" scope="prototype">
<property name="proxyInterfaces" value="my.Interface"/>
<property name="target" ref="my.BeanTarget"/>
<property name="interceptorNames">
<list>
<value>someInterceptor</value>
</list>
</property>
</bean>

<bean name="my.BeanTarget" class="my.InterfaceImpl" scope="prototype">
<property name="foo" ref="bar"/>
</bean>

一切正常;在 pre-Spring v3 世界中,我像这样使用它

ApplicationContext ctx = ...;
my.Interface foo = (my.Interface) ctx.getBean("my.Bean"); // cast is necessary

在 Spring 3 中,可以进行类型安全查找,例如:

my.Interface foo = ctx.getBean(my.Interface.class);

同样,这对普通 bean 很有效,而对于代理 bean,我得到的是 my.BeanTarget 而不是 my.Bean。我试图内联 my.BeanTarget(如 Spring 文档中所示)以使其隐藏,但我得到的只是

org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [my.Interface] is defined: expected single bean but found 0: 

那么是否可以对代理 bean 使用类型安全的 bean 查找,如果是的话 - 如何实现?

最佳答案

这里的问题是 ProxyFactoryBean 上的 scope="prototype"

上下文只会急切地初始化单例 bean 定义。非单例范围的 bean 仅在需要时才初始化。这意味着当您向上下文询问给定类型的 bean 时,上下文无法初始化那些非单例 bean 以询问它们的类型,它必须完全依赖 bean 定义中的信息。

ProxyFactoryBean 的情况下,生成的代理的类型由需要完全初始化 bean 的复杂逻辑决定。如果没有该初始化,ProxyFactoryBean 只能将目标类型报告为 null

除了使用单例 bean 定义,或者通过名称明确请求 bean 之外,我不能说解决这个问题的方法,例如

<bean id="my.Interface"> class="ProxyFactoryBean"... >

然后:

ctx.getBean(MyInterface.class.getName());

在这里,我们使用 bean 名称的约定作为它们实现的接口(interface)。

关于java - ApplicationContext.getBean(Class clazz) 不适用于代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3574092/

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