Luciano Borges
Luciano Borges

Reputation: 827

How inject a Singleton class annotated with @Startup? @Inject, @Resource, @EJB ou BeanManager?

I have a class like this:

@Singleton
@Startup
@Default
public class A {

    private Manager manager; // Manager is an interface

    @PostConstruct
    public void init() {
      if (some rule is true) {
         manager = new ManagerA();
      } else {
         manager = new ManagerB();
      }
    }

    public Manager getManager() {
       return manager;
    }

}

Now I have a endpoint JAX-RS like this:

@Path("mypath")
public class B {

    // @Inject vs @Resource vs @EJB - my doubt
    private A objA;

    @POST
    @Path("resource")
    @Consumes("application/json")
    @Produces("application/json")
    public Response myMethod(String param) {

        objA.getMamager().executeSomeMethod(param);

        return Response.status(HttpStatus.SC_OK).build();
    }
}

When I go inject the object it takes errors regardless of the annotation that I use. Some errors:

How to solve it?

Upvotes: 2

Views: 2164

Answers (1)

him
him

Reputation: 608

you probably have a race condition with your @Singleton @Startup bean and something it depends on. i've seen this several times myself. especially when the @Startup bean depends on another facility that the container has to initialize (q.v. JPA, JMS, CDI, etc.). if this is the case, remove the @Startup and just let the bean get initialized when it gets first injected into a dependent.

if you really, really, really need the bean to be @Startup, try to isolate what dependency it is failing on, and mark that dependency in the @DependsOn(depends="blah blah blah") annotation.

another workaround i have used, if you cannot remove the @Startup, isolate the dependency and lazy inject it via JNDI (old school). sometimes, all the bells and whistles just get in the way of "how it's really done." /grin

caveat emptor

Upvotes: 1

Related Questions