首页 > 解决方案 > 使用 Spring 构造子类而无需显式强制转换

问题描述

示例类:

动物.java

public class Animal {
    Animal(){
    }
}

狗.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();
            }

动物.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变量声明为 anAnimal会在获取 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,我不明白为什么我会在这里得到一个未找到类的异常。任何帮助将不胜感激。谢谢!

编辑:修正了小写的狗错字

标签: javaxmlspringinheritancejavabeans

解决方案


推荐阅读