问题描述
示例类:
Animal.java
public class Animal {
Animal(){
}
}
Dog.java
public class Dog extends Animal {
Dog(){
}
}
春季电话
...
// Dog dog = null; // this works
Animal dog = null; // does not work
ApplicationContext appContext = null;
String path = "animal.xml";
try
{
appContext = new FileSystemXmlApplicationContext("/" + path);
GenericbeanfactoryAccessor gbfa = new GenericbeanfactoryAccessor(appContext);
dog = gbfa.getBean("Dog");
dog.init(color);
return dog;
}
catch (Exception e)
{
LOGGER.info("Bean creation failure,error is: " + e);
return new Animal();
}
animal.xml:
<bean id="Animal" class="test.Animal">
</bean>
<bean id="Dog" class="test.Dog" parent="Animal" >
</bean>
为准系统示例道歉,但是我对此特定问题有疑问。 Dog类无法在代码中显式调用,因为它可能存在或可能不存在。如果该程序包存在,我想用Spring创建Dog类,但如果不存在,就返回一个动物。
如果我将dog
变量显式声明为Dog
而不是Animal
,则此代码有效。但是,由于代码可能没有Dog
软件包,所以我不能这样做。将dog
变量声明为Animal
会在获取ApplicationContext时出错。
12 21:01:09.589 [main] INFO - Bean creation failure,error is: org.springframework.beans.factory.CannotLoadBeanClassException:
Cannot find class [test.Dog] for bean with name 'Dog' defined in file [animals.xml];
nested exception is java.lang.classNotFoundException: test.Dog
请记住,如果将dog
声明为Dog
而不是Animal
,那么一切都会正常工作,我不明白为什么我会在这里得到一个找不到类的异常。任何帮助将不胜感激。谢谢!
编辑:修复了小写字母狗的错字
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)