Subresouce和CDI注入问题 [英] Subresouce and CDI Injection Issue

查看:162
本文介绍了Subresouce和CDI注入问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是jax-rs的新手,我被子资源困住了。看一看。

I am new to jax-rs and i am stuck with subresources. Take a look.

这不起作用

@Path(..)
public class Test
{
 @Path(...)
 public SubResource getSub(){
  return new SubResource();
 }
}

public class SubResource {
 @Inject
 private MyBean myBean;

 @GET
 public String getStr(){
  return myBean.getStr(); // myBean is null, injection didnt work properly
}

这有效,但为什么? ?????? b

this works, but why????

@Path(..)
public class Test
{
 @Context
 private ResourceContext context;

 @Path(...)
 public SubResource getSub(){
  return context.getResource(SubResource.class);
 }
}

public class SubResource{
 @Inject
 private MyBean myBean;

 @GET
 public String getStr(){
  return myBean.getStr(); // myBean is not null anymore, why?
}

为什么CDI Injection可以与ResoureContext一起使用?

Why CDI Injection works with ResoureContext?

推荐答案

这与子资源或JAX-RS没有任何关系。原则上,这是关于CDI注入的工作原理。

This has nothing do to with subresources or JAX-RS. In principle, this is about how CDI injection works.

首先,你的工作样本不合适。或者确切地说,这一点:

Firstly, your not working sample. Or to be precise, this bit:

@Path(...)
 public SubResource getSub(){
  return new SubResource();
 }

您正在创建 SubResource 实例您自己通过 new 关键字。因此,CDI对其存在没有任何线索,并且对这种对象完全没有控制权。因此,CDI无法向此对象注入任何内容。

You are creating the SubResource instance yourself via the new keyword. Therefore CDI has no clue about it existing and has absolutely zero control over such object. Therefore, CDI cannot inject anything into this object.

现在到工作样本:

@Context
 private ResourceContext context;

 @Path(...)
 public SubResource getSub(){
  return context.getResource(SubResource.class);
 }

在这种情况下,您注入了一个上下文(CDI管理的对象已经)并告诉它为您检索资源。因此,您让CDI容器处理对象创建及其生命周期。由于它管理创建,它也可以解决注入点并注入 MyBean

In this case, you injected a context (a CDI managed "object" already) and tell it to retrieve the resource for you. Therefore you let the CDI container handle the object creation and its lifecycle. And since it manages creation, it can also resolve injection points and inject MyBean.

一般来说,当你想要使用CDI,你几乎不能通过 new 创建对象。明显的例外是生产者,但我们不是在这里谈论它们。

Generally, when you want to use CDI, you barely ever create objects via new. The obvious exception are producers, but we are not talking those here.

这篇关于Subresouce和CDI注入问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆