传递给子类的constructor-arg时"无法解析匹配的构造函数"错误

dnc*_*253 0 java inheritance spring constructor

我有以下课程:

public abstract class ParentClass
{
    public ParentClass()
    {
        throw new RuntimeException("An ID must be specified.");
    }

    public ParentClass(String id)
    {
        this(id, DEFUALT_ARG_VALUE);
    }

    public ParentClass(String id, int anotherArg)
    {
        this.id = id;
        //stuff with anotherArg
    }

    public abstract void doInstanceStuff();
}

public class ChildClass extends ParentClass
{
    @Override
    public void doInstanceStuff()
    {
        //....
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的应用程序上下文中我有这个:

<bean id="myChildInstance" class="com.foo.bar.ChildClass " scope="singleton">
    <constructor-arg value="myId" />
</bean>
Run Code Online (Sandbox Code Playgroud)

问题是,当服务器启动时,我收到以下错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ivpluginHealthCheckTest' defined in ServletContext resource [/WEB-INF/spring/root-context.xml]: Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
Run Code Online (Sandbox Code Playgroud)

看到错误,我尝试添加不同的属性,但没有运气.我最终得到了这样的东西:

<bean id="myChildInstance" class="com.foo.bar.ChildClass " scope="singleton">
    <constructor-arg value="myId" index="0" type="java.lang.String" name="id" />
</bean>
Run Code Online (Sandbox Code Playgroud)

我仍然得到同样的错误.

我尝试将相同的构造函数添加到我的子类中,并super()使用适当的参数调用每个构造函数,这似乎可以解决它.但是,我不想在所有子实例中添加相同的构造函数,并且必须使用父类维护它们.

是否有一些原因Spring无法调用继承的构造函数来实例化该类?我能做些什么来使这项工作?

Roh*_*ain 5

调用继承的构造函数来实例化该类?

构造函数永远不会被继承,它实际上没有意义.构造函数只是初始化该特定类中的状态.您不能指望构造函数Parent初始化Child类的状态.这Child只是类中构造函数的工作.

所以,不,你不能做你想做的事.这不是Spring的问题.这是非常基础的.