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

时间:2016-03-08 18:51:28

标签: java-ee ejb 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");
  // ...
} 

正在从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
  }
}

应该被注射的Dao

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进一步发展的方式实施工厂?感谢。

1 个答案:

答案 0 :(得分:2)

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

当容器创建对象时,对象只执行CDI注入,或者将其自身注入某个地方,或者它是托管EE组件之一。

Net,您无法新建EJB或任何CDI bean并且其中包含任何CDI服务。

相关问题