Could not instantiate bean : Constructor threw exception; nested exception is java.lang.NullPointerException

后端 未结 3 1415
自闭症患者
自闭症患者 2021-02-19 23:08
package baseDao;

public interface BaseDao {

    public void create(Object obj);
    public void delete(Object obj);
    public void update(Object obj);
    public void         


        
相关标签:
3条回答
  • 2021-02-19 23:57

    The problem is here:

    @Autowired
    private  SessionFactory usermanagementSessionFactory;
    private  Session session = usermanagementSessionFactory.getCurrentSession();
    

    The sessionFactory needs to be autowired, but this only happens after construction. Construction involves the second line being executed - which uses the unset factory. Hence you get a null pointer exception.

    Even though your class doesnt have a constructor, construction of an instance can still thow an exception as a result of field initialisation, as in this case.

    0 讨论(0)
  • 2021-02-20 00:03

    Move the session initialization to below method

    @PostConstruct
    public void init(){
          session = usermanagementSessionFactory.getCurrentSession();
    }
    
    0 讨论(0)
  • 2021-02-20 00:12

    You are trying to initialize session object, when usernameSessionFactory object is not initialized yet.

    In a class, all Spring @Autowired objects are initialized just after the construction of the instance of such class is done.

    private  Session session = usermanagementSessionFactory.getCurrentSession();
    

    But if an instance decleared in a way like the above code, will be initialized earlier than construction, in a way that they can even be used as parameters of construction.

    @Autowired
    private  SessionFactory usermanagementSessionFactory;
    private  Session session;
    
    @PostConstruct
    public void init() {
        session = usermanagementSessionFactory.getCurrentSession();
    }
    

    Above code, will initialize session object after the construction, which means usermanagementSessionFactory is ready and not null.

    Hopefull it helps..

    0 讨论(0)
提交回复
热议问题