Skip to main content
edited tags
Link
James McMahon
  • 50k
  • 69
  • 212
  • 288
Source Link
Vinnie
  • 12.8k
  • 15
  • 63
  • 80

Auto-cast Spring Beans

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.

For instance, given this config file

<bean id="bean-name" class="SimpleSpringBean" scope="prototype"> <property name="myValue" value="simple value"></property> </bean> 

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.

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.