自动浇铸弹簧豆 [英] Auto-cast Spring Beans
问题描述
有没有办法自动转换Spring bean到应用程序上下文XML中定义的类?我想避免把类型信息关于bean在2个地方....在xml配置文件和代码作为一个转换。
Is there a way to auto-cast Spring beans to the class defined in the application context XML? I'd like to avoid putting type information about the beans in 2 places.... in the xml configuration file and also in the code as a cast.
例如,给定此配置文件
<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个地方。
Can I call ApplicationContext.getBean("bean-name")
in such a way as to avoid directly casting the return type to SimpleStringBean
. I know I can also call ApplicationContext.getBean("bean-name", SimpleSpringBean.class)
to avoid the cast itself, but I still have the type info in 2 places.
看起来Spring可以获取类信息( ApplicationContext.getType
),
It seems that Spring can get the class info (ApplicationContext.getType
) or by getting the type from the bean itself, but no way to automatically cast the type without programmer intervention.
推荐答案
我同意Sii,你应该避免调用getBean作为尽可能多的。
I agree with Sii, you should avoid calling getBean as much as you can. Just wire your beans to classes that depends on them.
仍然,如果你有一个类保存应用程序上下文,你可以提供一个包装器通用的方法,如下面的:
Still, if you have a single class that holds the application context, you can provide a wrapper generic method like the following:
class MyContextHolder{
ApplicationContext appContext;
......
@SuppressWarnings("unchecked")
public static <T> T getBean(String beanName)
{
return (T)appContext.getBean(beanName);
}
}
Then you can call it without casting
MyClass mc = MyContextHolder.getBean("myClassBean");
这篇关于自动浇铸弹簧豆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!