I am developing a simple REST application using Java EE 7 with Glasfish 4 as AS for learning purposes and getting an annoying NullPointerException I cannot explain why.
I have a model class:
package com.test.model;
@Entity
@Table(name = "USUARIO")
public class User implements Serializable {
private String login;
@Id public String getLogin() {
return login;
}
}
A UserApiController class:
package com.test.api.controller;
@Path("/users")
public class UserApiController {
@Inject private UserService userService;
@Path("/all") @GET @Produces("application/json")
public JsonArray getAll() {
// call to userService.findAll method, raises NPE
}
(The Persistence class is based on question http://ift.tt/1HgdomQ)
A UserPersistence class that holds the EntityManager:
package com.test.persistence;
@Stateless
public class UserPersistence extends PersistenceFacade<User, String> {
@PersistenceContext(unitName = "test")
private EntityManager entityManager;
public final List<User> findAll() {
TypedQuery<User> query = entityManager.createQuery("select u from User u", User.class);
List<User> queryResult = query.getResultList();
if (queryResult == null) {
return new ArrayList<User>();
}
return queryResult;
}
}
A UserService class:
package com.test.service;
@Stateless
public class UserService {
@Inject private UserPersistence userPersistence;
public final List<User> findAll() {
return userPersistence.findAll();
}
}
And finally the ApiConfig class:
package com.test.api;
@ApplicationPath("/api")
public class ApiConfig extends javax.ws.rs.core.Application { }
Also I have a beans.xml file in src/main/resources/META-INF with this content:
<beans xmlns="http://ift.tt/19L2NlC"
xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="http://ift.tt/19L2NlC http://ift.tt/18tV3H8"
version="1.1" bean-discovery-mode="all">
</beans>
When I deploy the project (Maven) and run the server it starts correctly, but when I try to access localhost:8080/test/api/users/all, I get a NPE error when trying to invoke the findAll() method from userService.
Advertencia: StandardWrapperValve[com.test.api.ApiConfig]: Servlet.service() for servlet com.test.api.ApiConfig threw exception
java.lang.NullPointerException
at com.test.service.UserService.findAll(UserService.java:21)
at com.test.api.controller.UserApiController.getAll(UserApiController.java:30)
Debugging I can see that userPersistence field is null when it is accessed. I cannot see why this is null but userService is instantiated correctly, for example.
Aucun commentaire:
Enregistrer un commentaire