I am looking for a way to inject a custom class @RequestScoped
into my JAX-RS endpoint @Stateless
:
I want every time an application receives a request, my custom class is injected into my JAX-RS endpoint.
Custom class:
@RequestScoped
public class CurrentTransaction {
private String user;
private String token;
@PersistenceContext(name="mysql")
protected EntityManager em;
@Inject HttpServletRequest request;
public CurrentTransaction() {
this.user = request.getHeader("user");
this.token = request.getHeader("token");
}
}
So, I declare my class CurrentTransaction
as @RequestScoped
for initialization every time a request is received. To do this, I need to access HttpServletResquest
to get the header options.
JAX-RS Endpoint:
@Stateless
@Path("/areas")
public class AreasEndpoint {
@PersistenceContext(unitName = "mysql")
protected EntityManager em;
@Inject
protected CurrentTransaction current_user_service;
@POST
@Path("postman")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Authentication
public Response create(AreaRequest request) {
if (this.current_user_service.getUser() == null) {
System.out.println("Go!!!");
return Response.status(Status.FORBIDDEN).build();
} else {
System.out.println("---- user: " + this.current_user_service.getUser());
System.out.println("---- token: " + this.current_user_service.getToken());
}
}
}
CDI arrives to execute the class constructor CurrentTransaction
. However, the request field is HttpServletRequest
not initialized (entered).
What am I doing wrong?