2015-10-12 135 views
0

编辑:我的问题不是为什么Spring bean为null,但为什么继承bean是null?建议的答案解释了为什么新的操作员不能使用自动装配。但我的问题是关于继承。 我有两个类:Java继承spring autowired属性为空

@Transactional 
public class A { 

    @Autowired 
    protected SessionFactory sessionFactory; 

    //other methods 
} 

public class B extends A { 

    Session session = sessionFactory.getCurrentSession(); 

    //other methods 
} 

Main.java我得到NPE - B类不具备获得财产A(((我不明白为什么(((

A inst1 = new B(); - dont have access to body of B. 
B inst2 = new B(); - inside class B sessionFactory is null(((

我做错了什么?我需要访问B的body,以及上级的属性Bean sessionFactory正在工作:

ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml"); 
     SessionFactory sessionfactory = (SessionFactory) context.getBean("sessionFactory"); 
     Session session = sessionfactory.getCurrentSession();//works 
+2

当propertyA被声明为原语时,它如何为null?似乎很奇怪! – Abubakkar

+1

它应该工作正常..你有一些其他的错误,我猜 – stinepike

+0

发布一些真实的代码,所以我们可以验证你的问题。 – khelwood

回答

0

如果你得到NPE,是因为sessionFactory没有被注入,而是你没有访问sessionFactory属性。

如果在加载应用程序上下文后可以获得sessionFactory的实例,那么该bean是正确配置的。

所以我相信你的问题必须与自动装配注释配置相关。你有<context:annotation-config />进入你的应用程序上下文吗?或者是否有定义到应用程序上下文中的类org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor的bean? - 您的beans xml节点