【发布时间】:2023-04-06 01:21:01
【问题描述】:
我在 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>
这一切都很好;在 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 查找,如果可以,如何使用?
【问题讨论】:
-
你真的需要直接与上下文交互吗?我的大多数应用程序只需要引导它,然后使用依赖注入处理其他所有内容(这适用于代理 bean)。我已经完成了一些需要访问上下文的框架工作,但根据我的经验,这种情况很少见。
-
我们的系统比较宽,有些位和类不是Spring诞生的(也不可能),所以他们必须使用beanFactory/appCtx来获取必要的依赖。