0

we have mixed the usage of CDI and EJB in our application. At startup, we receive the error Caused by: org.jboss.weld.context.ContextNotActiveException: WELD-001303: No active contexts for scope type javax.enterprise.context.RequestScoped.

We don't understand where exactly the problem is, so here is just the overall structure of the code:

@Stateless
public class SomeFacade {
    @Inject
    private SomeService someService;
}

@Stateless
public class SomeService {
    @Inject
    private SomeDao someDao;
}

@Stateless
public class SomeDao {
    @Inject
    private EntityManager entityManager;
}

@ApplicationScoped
public class EntityManagerProducer {
   @Produces
   @ApplicationScoped
   public EntityManagerFactory createEntityManagerFactory() {
         EntityManagerFactory emf = Persistence.createEntityManagerFactory("one");
     return emf;
   }

   public void close(@Disposes EntityManagerFactory entityManagerFactory) {
       entityManagerFactory.close();
   }

   @Produces
   public EntityManager createEntityManager(EntityManagerFactory entityManagerFactory) {
      return entityManagerFactory.createEntityManager();
   }
}

Is there something we can change in general?

user1414745
  • 1,317
  • 6
  • 25
  • 45
  • Can you pinpoint where is the exception coming from? E.g. which injection or bean call. From your code there is no visible place where you would be using `RequestScoped`. And EJB's `Stateless` are, accordingly to spec, viewed as `Dependent` by CDI. – Siliarus Aug 10 '18 at 11:12

2 Answers2

2

The error is raised because your code tries to access a request-scoped CDI bean in a moment when there's no request scope. Request scope is only created for incoming requests (HTTP requests via Servlet or JAX-RS, JMS MDBs, asynchronous EJB calls, etc.).

If you get this error during startup, I guess you access a request-scoped bean before CDI is fully started, e.g. from a singleton EJB. Try moving your code into a CDI that starts on start-up after CDI is initialized with:

@Dependent
public class CDIStartupBean {
    public void startup(@Observes @Initialized(ApplicationScoped.class) Object event) {
        // Start-up code here. The CDIStartupBean can inject request-scoped beans
    }
}
OndroMih
  • 7,280
  • 1
  • 26
  • 44
0

Ondrej, your answer was helpful but was not quite the solution in my case.

First, I somehow resolved the start-up issues, but received the same error when handling arriving messages / REST requests. The solution was to annotate the service class with @ActivateRequestContext. This enabled CDI injections in all classes that are used by the servive.

user1414745
  • 1,317
  • 6
  • 25
  • 45