简体   繁体   English

java继承的spring autowired属性为null

[英]java inherited spring autowired property is null

EDIT: My question is not about why Spring bean is null, but about why inherited bean is null? 编辑:我的问题不是关于为什么Spring bean为null,而是关于为什么继承的bean为null? Proposed answer explains why new operator does not work with autowiring. 建议的答案解释了为什么新操作员无法使用自动装配。 But my question is about inheritance. 但是我的问题是关于继承的。 I have two classes: 我有两节课:

@Transactional
public class A {

    @Autowired
    protected SessionFactory sessionFactory;

    //other methods
}

public class B extends A {

    Session session = sessionFactory.getCurrentSession();

    //other methods
}

In Main.java I get NPE - class B dont have access to property A((( And I dont understand why((( 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(((

What I do wrong? 我做错了什么? I need to have access to body of B, and to properties of superior class. 我需要访问B的正文以及上级的属性。 Bean sessionFactory is working: Bean sessionFactory正在工作:

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

If you are getting NPE, is because sessionFactory is not being injected, instead that you haven't access to sessionFactory property. 如果您正在获取NPE,那是因为没有注入sessionFactory ,而是您没有访问sessionFactory属性的权限。

If you can get an instance of sessionFactory after loading your application context, then this bean is right configured. 如果在加载应用程序上下文之后可以获取sessionFactory的实例,则该bean已正确配置。

So I believe your problem has to be related with autowired annotation config. 因此,我认为您的问题必须与自动装配的注释配置有关。 Do you have <context:annotation-config /> into your application context? 您是否在应用程序上下文中包含<context:annotation-config /> or have you got a bean of class org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor defined into your application context? 还是在应用程序上下文中定义了类org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor的bean? - Has your beans xml node -具有您的bean xml节点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM