CDI不在从工厂模式实现创建的对象中工作

Tob*_*sse 5 ejb java-ee cdi websphere-liberty

我试图在这里解决一些问题:注入仅适用于我的应用程序的第一层,但随后它停止,并且从我的工厂模式实现返回的对象中所有@Inject注释属性都为null.我读了很多关于让CDI与JAX-RS一起工作有问题的人,但这似乎不是我的问题.我觉得我错过了一些注释,或者我没有看到所有树木前面的木头(正如我们在这里所说);-)

编辑:是否有一个示例项目与我在这里发布的代码进行仔细检查.现在我意识到我过度简化了:事实上我正在使用工厂模式来获取我的服务,这可能会中断托管上下文.请参阅增强示例:

我们走吧.

第一层:JAX-RS应用程序,一切都很好

@RequestScoped
@Path("/somePath/someResource")
public class SomeResource {
   @Inject
   ISomeServiceFactory someServiceFactory;

   @POST
   @Produces(MediaType.APPLICATION_JSON)
   @Consumes(MediaType.APPLICATION_JSON)
   public SomeResponse someMethod(@PathParam("foo") final String foo) {
      ISomeService myService = someServiceFactory.getService(ServiceCatalog.valueOf(foo));   // works, we jump in there!
      myService.someMethod();
   }

}

public enum ServiceCatalog {
  STANDARD("standard"), ADVANCED("advanced"), FOO("foo");
  // ...
} 
Run Code Online (Sandbox Code Playgroud)

正在从REST API调用中选择基于已知参数(Enum)值的实现的已损坏服务工厂:

public interface ISomeServiceFactory {
  public ISomeService getService(ServiceCatalog serviceType);
} 

@Stateless
public class SomeServiceFactory implements ISomeServiceFactory {
  public ISomeService getService(ServiceCatalog serviceType) {
    if(serviceType.equals(ServiceCatalog.FOO)) {
      return new FooService();  // will break CDI context
    } else if (...) {
      // ...
    } else {
      return new DefaultService(); // will also break CDI context
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

第二层:有些EJB,麻烦在这里

// Interface: 

public interface ISomeService {
  public void someMethod();
}

// Implementation:

@Stateless
public class SomeService implements ISomeService {
  @Inject
  private ISomeDao someDao;    // this will be null !!!

  @Override
  public void someMethod() {
    someDao.doSomething()   // exception thrown as someDao == null
  }
}
Run Code Online (Sandbox Code Playgroud)

应该注射的Dao

public interface ISomeDao {
  public void someMethod();
}

@Stateless
public class SomeDao implements ISomeDao {
  public void someMethod() {}
}
Run Code Online (Sandbox Code Playgroud)

现在,在运行时,WebSphere Liberty告诉我(以及其他绑定......):

 com.ibm.ws.ejbcontainer.runtime.AbstractEJBRuntime
 I CNTR0167I: The server is binding the com.ISomeDao interface of the
 SomeDao enterprise bean in the my.war module of the my application.  
 The binding location is: java:global/my/SomeDao!com.ISomeDao
Run Code Online (Sandbox Code Playgroud)

我有一个beans.xml:

 <beans
   xmlns="http://xmlns.jcp.org/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee    http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
   bean-discovery-mode="all">
 </beans>
Run Code Online (Sandbox Code Playgroud)

似乎新的SomeService()打破了一切,你能否建议如何以一种使CDI进一步发展的方式实施工厂?谢谢.

cov*_*ner 2

在修改后的问题中,您表明实际上并没有将 EJB 注入到 Web 服务中,它是通过工厂间接更新的。

仅当容器创建对象时,对象才会执行 CDI 注入,无论是通过自身注入某处还是将其作为托管 EE 组件之一。

Net,您不能新建 EJB 或任何 CDI bean 并在其中包含任何 CDI 服务。