Bean定义和名称查找

时间:2015-05-09 06:41:31

标签: java spring

我试图通过spring's name lookup来解决问题:

<bean id="test" class="com.badmitrii.TestBean" />

<bean id="anotherTest" class="com.badmitrii.AnotherTestBean">
    <lookup-method bean="test" name="getString"/>
</bean>

public class TestBean {

    private String testBean = "Test bean";

    //GET, SET

    public String getString(){
        return "String";
    }
}

public class AnotherTestBean {

    private String testBean = "Another test bean";

    //GET, SET

    public String getString(){
        return "Overriden string";
    }
}

但是当我试图运行应用程序时,我得到以下异常:

Exception in thread "main" java.lang.ClassCastException: com.pac.TestBean cannot be cast to java.lang.String
    at com.pac.AnotherTestBean$$EnhancerBySpringCGLIB$$d6d0f4c6.getString(<generated>)

就行:

System.out.println(((AnotherTestBean) context.getBean("anotherTest")).getString());

这有什么不对?

1 个答案:

答案 0 :(得分:1)

您说bean“anotherTest”的类型为com.badmitrii.AnotherTestBean,并且是通过调用bean getString()的方法test创建的。

但是此方法不返回com.badmitrii.AnotherTestBean的实例。它返回一个String。因此例外。