我正在寻找一种方法,以便将@RequestScoped
自定义类注入我的@Stateless
JAX-RS端点:
我希望每次应用程序收到请求时,我的自定义类都会在我的JAX-RS端点中注入。
自定义类:
@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");
}
//getters and setters ...
}
因此,我将CurrentTransaction
类声明为@RequestScoped
,以便在每次收到请求时进行初始化。
为此,我需要访问HttpServletResquest
以获取标头参数。
JAX-RS端点:
@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到达以执行CurrentTransaction
类的构造函数。但是,HttpServletRequest
请求字段未初始化(注入)。
我做错了什么?
答案 0 :(得分:1)
关于这一点的最新答案 - 对其他读者可能有用:CDI中的依赖注入按以下顺序完成:
@PostConstruct
带注释的方法被调用最后一点是您想要进一步初始化需要访问注入字段的位置:
@Inject HttpServletRequest request;
public CurrentTransaction() {
// field injection has not yet taken place here
}
@PostConstruct
public void init() {
// the injected request is now available
this.user = request.getHeader("user");
this.token = request.getHeader("token");
}