【发布时间】:2010-10-23 04:01:56
【问题描述】:
有没有办法将 Spring bean 自动转换为应用程序上下文 XML 中定义的类?我想避免将有关 bean 的类型信息放在 2 个位置......在 xml 配置文件中以及作为强制转换的代码中。
例如,给定这个配置文件
<bean id="bean-name" class="SimpleSpringBean" scope="prototype">
<property name="myValue" value="simple value"></property>
</bean>
我可以调用ApplicationContext.getBean("bean-name") 以避免直接将返回类型转换为SimpleStringBean。我知道我也可以调用 ApplicationContext.getBean("bean-name", SimpleSpringBean.class) 来避免演员本身,但我仍然在 2 个地方有类型信息。
Spring 似乎可以获取类信息 (ApplicationContext.getType) 或通过 bean 本身获取类型,但没有程序员干预无法自动转换类型。
【问题讨论】:
-
无论哪种方式,您都需要在两个地方提供类型信息,因为您需要声明变量的类型:
SimpleStringBean var = ApplicationContext.getBean("bean-name");但这看起来像是在中断 java:getBean(String)是什么类型返回?
标签: java spring casting javabeans