RequestScoped bean CDI

时间:2015-05-05 07:47:47

标签: java jax-rs httprequest cdi stateless

我正在寻找一种方法,以便将@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请求字段未初始化(注入)。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

关于这一点的最新答案 - 对其他读者可能有用:CDI中的依赖注入按以下顺序完成:

  1. 调用构造函数
  2. 注入
  3. 字段
  4. @PostConstruct带注释的方法被调用
  5. 最后一点是您想要进一步初始化需要访问注入字段的位置:

    @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");
    }