简体   繁体   中英

Java ~ Service Layer failed to call DAO layer and throw NullPointerException

Am i wrongly implemented the way to call DAO layer? The breakpoint is not hit inside the DAO method and exception throw only mentions about NullPointerException.Kindly advice. Thank You

Service Layer: public class BookServiceImpl {

    private static BookServiceImpl myInstance;
    private BookDAO dao;

    public static BookServiceImpl getInstance() {
        if (myInstance == null) {
            myInstance = new BookServiceImpl();
        }
        return myInstance;
    }

    public List<Book> getBookList(BookDTO dto) {
        return dao.getBookList(dto);
    }

}

DAO Layer public class BookDAO { private BookDAO () { sqlService = Services.get(SqlService.class); }

    public static BookDAO getInstance() {
        if (myInstance == null) {
            myInstance = new BookDAO ();
        }
        return myInstance;
    }

}

Looks like you never set value to:

private BookDAO dao;

in BookServiceImpl , causing this line:

return dao.getBookList(dto);

to throw NPE as dao is null.

You need to instantiate it before accessing it.

In BookServiceImpl

private BookDAO dao;  // not initialize 

and then you are calling

return dao.getBookList(dto);  // here dao is null.

Then you will get NullPointerException .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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