Spring - 通过父级注入时未设置子类属性

时间:2014-10-14 17:57:17

标签: spring inheritance subclass parent

鉴于以下XML Spring代码:

<bean id="baseCarFacade" class="com.foo.BaseCarFacade">
    <property name="engineFacade" ref="engineFacade" />
</bean>

<bean id="engineFacade" class="com.foo.EngineFacade" />

<bean id="childCarFacade" class="com.foo.ChildCarFacade" parent="baseCarFacade" />

和这个Java代码:

public class BaseCarFacade implements IBaseMemberFacade {

    public void setEngineFacade(EngineFacade engineFacade) {
        this.engineFacade = engineFacade;
    }

    ...
}

public class EngineFacade {

    ...
}

public class ChildCarFacade extends BaseCarFacade {

    public void doSomethingSpecial() {

        someObject = engineFacade.doSomethingReallySpecial();
    }

    ...
}

我有一个属性,我想在子类(childCarFacade)中注入(engineFacade),这可能会为父类的其他子项(BaseCarFacade)注入。我没有在所有子类中冗余地拥有此属性,而是希望将它放在父级别,然后只需在上面显示的任何子项中使用它,我将调用&#34; doSomethingReallySpecial()& #34;

但是,每当我执行此代码时,我都会得到一个运行时空指针异常,如下所示:

  

引起:java.lang.NullPointerException at   com.foo.EngineFacade.doSomethingReallySpecial(EngineFacade.java:48)

这是我的bean实例化的一行:

  

预先实例化单身人士   org.springframework.beans.factory.support.DefaultListableBeanFactory@32273227:   定义bean   [winkInternalLifecycleManager,winkInternalLifecycleManagersRegistry,winkInternalRegistryPostProcessor,winkInternalLifecycleManagerPostProcessor,winkInternalDependenciesInjectionPostProcessor,winkInternalDeploymentConfiguration,winkInternalRequestProcessorBuilder,winkInternalDefaultPropertiesFactory,winkInternalPropertiesFactory,winkInternalPropertyPlaceholderConfigurer,winkInternalNullContant,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation .internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.apache.wink.spring.Registrar#0,jaxbProvider,jacksonObjectMapper,jacksonAnnotationIntrospector,primaryAnnotationIntrospector,secondaryAnnotationIntrospector,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,propertyPlaceholderConfigurer ,allProperties,数据源,动态缓存,CO mmonCache,transactionManager的,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,JdbcTemplate的, baseCarFacade,engineFacade,childCarFacade,...

您可以看到最后一个似乎正确实例化。

有人能指出我的方式错误吗?我觉得这应该很简单......

2 个答案:

答案 0 :(得分:1)

也许尝试在父级中暴露getter并使用getEngineFacade()。doSomethingReallySpecial()?

答案 1 :(得分:1)

嗯,这非常令人尴尬,但事实证明我在Null Pointer Exception看起来太过深了。本质上,doSomethingReallySpecial()方法中有一个NPE,根本不在engineFacade中。 engineFacade整个时间都设置正确。这意味着我上面发布的原始代码(正如Eric.B所提到的)确实可以正常工作。

我很抱歉错过了这么简单的事情;希望最终别人会发现这个问题很有帮助..

感谢您的帮助Eric。 B和user1030367!