0
votes

My question based on Can't get SessionContext on EJB, I want to inject EJBContext into my code

My code is:

import javax.ws.rs.core.Context;

public class EjbContextTest {
    @Resource
    private EJBContext ejbContext;
    @Resource
    private SessionContext sessionContext;
    ......
}

I have a simple testing in activator, just want to verify if I can get an EJBContext by using CDI:

public void start(BundleContext context) throws Exception {

    EjbContextTest test = new EjbContextTest();

    if (test.getEjbContext() == null) {
       System.out.println("ejbContext is: null" );
    } else
       System.out.println("ejbContext rollback only is: " + 
           test.getEjbContext().getRollbackOnly());
    }

When deploying the bundle into glassfish 3.1.2 I can't get an instance of EJBContext:

2013-03-29 17:11:20,547|INFO|glassfish3.1.2|javax.enterprise.system.std.com.sun.enterprise.server.logging|
_ThreadID=15;_ThreadName=Thread-2;|-----------> ejbContext is: null*|#]

Please, if you have any suggestion, I will be glad to try it.

2
So you're unable to use @Resource to inject the contexts? - kolossus
Hi kolossus, it doesn't work by using @Resource, and also will get a exception in on deploy a bundle into Glassfish - alex
Hi alex, did you get the reason why @Resource doesn't work on EJBContext? - RicardoS

2 Answers

0
votes

You can't access EJB session beans or CDI beans by calling their constructors. Either of the following two should work:

  1. Inject using CDI (Or CDI-EJB integration)

    @Inject
    private EjbContextTest test;
    
  2. Inject using pure EJB annotation

    @EJB
    private EjbContextTest test;
    

then you can call test.getEjbContext().

This way, @Resource annotations are processed.

Hope it helps

0
votes

For those who still need in the future...

The injecton works using:

@Resource
private SessionContext ejbContext;

or

@Resource(mappedName = "java:comp/EJBContext") // adding 'mappedName' with JNDI name
private EJBContext ejbContext;