0

I've the below @Singleton EJBs:

@Singleton
public class RunBean {

  private int id = new Random().nextInt();

  public void printID() {
    System.out.println("ID = " + id);
  }

}
@Singleton
public class ParentBean {

  @Inject
  private RunBean runBean;

  public void start() {
    runBean.printID();
  }

}

I'm @Inject-ing them in the below web servlet:

public class Servlet extends HttpServlet {

  @Inject
  private RunBean runBean;

  @Inject
  private ParentBean parentBean;

  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      runBean.printID();  // out: ID = 69743
      parentBean.start(); // out: ID = 193
  }

}

I expected to see the same ID being printed. Why are they different?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Vladimir
  • 157
  • 2
  • 16
  • Is that `@javax.ejb.Singleton`? – Harald Wellmann May 20 '15 at 20:13
  • Yes what annotation class is that. – Robert Moskal May 20 '15 at 20:43
  • I suspect you might be a victim of a CDI quirk: either use only `@EJB` to inject your singletons everywhere (instead of `@Inject`) or add `@ApplicationScoped` to your `@Singleton`s and keep using `@Inject` – kolossus May 21 '15 at 03:31
  • Yes thank. RunBean is `javax.inject.Singleton`. But ParentBean is `com.google.inject.Singleton` (this implementation need for use library). So I can not inject CDI Singleton in `com.google.inject.Singleton`? But I need him there. What should I do to get bean? Use `new initialcontext().lookup`? – Vladimir May 21 '15 at 07:14
  • Do you deploy your application on a Java EE container? Or do you use 3rd party lib for injecting (e.g.:guice)? – Benjamin May 21 '15 at 10:16
  • Java EE. I use for deploy Jboss EAP 6.4 Guice use only for work with gwtrpcplus [http://code.google.com/p/gwtrpcplus/] – Vladimir May 21 '15 at 11:56
  • Google's implementation of `@Singleton` is just weird – kolossus May 21 '15 at 15:23
  • Thank you for the explanation. Really strange behavior. – Vladimir May 24 '15 at 19:33

1 Answers1

1

You should only @Inject EJBs (such as your @Singleton beans) on a JavaEE 7 or newer server.

In a Java EE6 environment you must use @EJB.

Steve C
  • 18,876
  • 5
  • 34
  • 37