2015-05-09 25 views
0

我想experen =換貨與spring's name lookupBean的定義和名稱查找

<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

您是說bean「anotherTest」類型爲com.badmitrii.AnotherTestBean,並且通過調用bean test的方法getString()創建。

但是這種方法不返回com.badmitrii.AnotherTestBean的實例。它返回一個字符串。因此是例外。

+0

我想,它應該用'TestBean'方法重寫getString的實現。所以實際上,'lookup-method'就是將方法的實現移動到spring-config,呵呵? –

+0

是的,我明白你的意思。 –

相關問題