CDI 不适用于从工厂模式实现创建的对象

CDI not working in objects created from factory pattern implementation

我想在这里解决一些问题:注入仅在我的应用程序的第一层上工作,但随后它停止并且所有@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");
  // ...
} 

已损坏 服务工厂正在根据来自 REST API 调用的已知参数(枚举)值选择实现:

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
    }
  }
}

第二层:一些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
  }
}

应该注入的道

public interface ISomeDao {
  public void someMethod();
}

@Stateless
public class SomeDao implements ISomeDao {
  public void someMethod() {}
}

现在在运行时 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

我有一个 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>

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

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

只有当容器创建对象时,对象才会执行 CDI 注入,或者是通过自身注入到某个地方,或者是托管 EE 组件之一。

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