Auto-cast Spring Beans

casting, java, javabeans, spring

Solution

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");

Problem

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.

Original source