Suppose there is an interface:

public interface BookDAO { public Book getBookByID(int id); } 

Class:

 public class BookDAOImpl implements BookDAO { public Book getBookByID(int id) { .....dowork } } 

And servlet:

 import javax.inject.Inject; @WebServlet("/management") public class BookStore extends HttpServlet { @Inject private BookDAO bookDAO; protected void doGet(HttpServletRequest req, HttpServletResponse resp) { List<Book> books = new List<>(); books = bookDAO.getALLBooks(); } } 

src\META-INF\bean.xml

 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd"> </beans> 

I NullPointerException on books = bookDAO.getALLBooks() , the method in a usual console form through new BookDAOImpl works out normally.

In Spring, @Repository and @Autowired + were used to specify where to scan, but what about @Inject ?

Thank!

  • Annotate BookDAOImpl , for example, @Named , @Stateless or some @...Scoped . - user194374
  • I tried in different variations - nothing has changed, maybe I missed something other than annotations? - CheshireK
  • Minimal content beans.xml created? - user194374
  • Updated the question, added information on bean.xml . - CheshireK
  • beans.xml should be in src/webapp/WEB-INF . - user194374

1 answer 1

  1. Config should be called beans.xml (you have s at the end skipped)
  2. @Stateless annotation is not needed, this is for EJB, for CDI you need one of the @ ... Scoped annotations
  • Mislead you with a typo, to my regret the name of the file beans.xml . The getALLBooks() method goes to the database via Connection, ResultSet, PreparedStatement , and @Inject not applied to them? - CheshireK
  • What container are you using? WildFly, Glassfish? Simple Tomcat CDI Won't Work Without Additional Libraries - Denis Zholobov
  • Ok, once again: beans.xml in META-INF - Denis Zholobov
  • Ok, check again: 1) beans.xml in META-INF; 2) @ApplicationScoped on BookDAOImpl, import javax.enterprise.context.ApplicationScoped; In the DAO itself, the idea is that you do not need to inject anything, you have a clean JDBC there, apparently. Yes, and in the servlet you have a List <Book> books = new List <> (); Is it generally compiled? - Denis Zholobov
  • List is simply inserted for example, the methods themselves through new work and work with the database. With @Inject, the creation of a class instance does not occur I have Tomcat, what libraries do I need to connect? - CheshireK