-->

@Inject gives a NullPointer Exception in java EE

2019-08-24 01:16发布

问题:

I'm trying to create a webservice that gives some results taken through hibernate from the database.

@Path("/book")
public class BookService {

    @Inject
    private dbController db;

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getBookTitle() {
        return "H2G2";
    }

    @GET
    @Path("/users")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getUsers(){

        List<UserEntity> users = db.getUsers();


        return Response.ok(users,MediaType.APPLICATION_JSON).build();
    }
}

the db variable whenever I call http://localhost/book/users is always null.

The dbController is:

public class dbController {

    @Inject
    private HibernateUtil util;

    public List<UserEntity> getUsers(){

        List<UserEntity> result = null;
        try{
            result = (List<UserEntity>) this.util.createQuery("select e from UserEntity e");
        }catch (Exception e){
            System.out.println(e.getMessage());
        }

        return result;
    }
}

and the HibernateUtil is:

public class HibernateUtil {

    private static final EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("NewPersistenceUnit");
    private EntityManager entityManager = null;


    private void createEntityManager(){
        if (this.entityManager==null){
            this.entityManager = entityManagerFactory.createEntityManager(); // here is your persistence unit name
        }


    }

    private void closeConnection(){
        this.entityManager.close();
        this.entityManager = null;
    }

    public List createQuery(String query) throws Exception{
        this.createEntityManager();
        List result;

        try{
            result = this.entityManager.createQuery(query).getResultList();
        }catch (Exception e){
            throw new Exception(e.getMessage());
        }

        return result;
    }


}

I'm using intellij and I added a break point at the db.getUsers() and set the variable db by adding new dbController(). However, the Intellij gives me the error "Class not loaded : controller.dbController".

The hibernate works for sure...so the problem is not there. It's the first time I'm trying to use Dependency Injection, but I'm not sure what I'm doing wrong.

Thanks

回答1:

You cannot inject POJO it has to be a Bean. So making it a bean requires the annotations, for example:

@Stateful
@LocalBean
public class dbController {..} // Should be DbController, start with CAPS

and

@Stateful // or maybe @Stateless ?
@LocalBean
public class HibernateUtil {..}

Then when you have a Bean it is not allowed to use static final so change like this is needed:

private EntityManagerFactory entityManagerFactory =
            Persistence.createEntityManagerFactory("NewPersistenceUnit");

But actually the easiest way to get EntityManager is just to inject it also. Like:

@PersistenceContext// maybe also with unit name (unitName = "whatever_the_unit_name_is")
private EntityManager em;