我有这样一个方法
package mytest;
public class TestImpl extends AbstractTest implements TestIfc{public void handler() { // TODO Auto-generated method stub } @Override public void test() { // TODO Auto-generated method stub }
}
public abstract class AbstractTest {public abstract void test();
}
public interface TestIfc {public void hander();
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
"><bean id="test" class="mytest.TestImpl" >
</beans>
ClassPathXmlApplicationContext c = new ClassPathXmlApplicationContext("application.xml");TestImpl test = (TestImpl)c.getBean(test);
会有 java.lang.ClassCastException
spring默认使用的是jdk的动态代理 ,必须要以下操作才可以TestIfc test = (TestIfc)c.getBean(test);
使用这个获取到bean不会有问题,但这样我就无法调用 方法 test() 了。
[quote]public abstract class AbstractTest {
public abstract void test();
} [/quote]
没存在的必要; 面向接口;才是该做的.
getBean();方法
你在配置中已经将这个bean实例化了,正如楼上所说的,你只需要在spring上下文中取出这个bean就可以了,实际上你应该在使用这个bean的其他类注入这个bean,如果你只是getBean这也提现不出spring的特长了
好像是这样的
TsetImpl testImpl = applicationContext.getBean("test");
TestIfc t = (TestIfc)applicationContext.getBean("test");
对,面向接口就OK了
貌似在applicationContext.xml中也改成