Search code examples
osgiglassfish-3cdiejb-3.1

OSGI: get reference to EJB from ServiceListener


I use OSGI, Weld and Glassfish3.1

I have an OSGI module with ServiceListener. In ServiceListener I need to enter the registered services to my database.
Initially I thought to write an EJB that goes to DB, and in ServiceListener add lookup/EJB injection that would bring EJB(The EJB and ServiceListener are in the same bundle).

However the lookup/EJB injection does not work:

    @EJB
private AdminService adminService;


     private class MyServiceListener implements ServiceListener {
            private AdminService adminService;

            public MyServiceListener(){
               adminService = (AdminService) ctx.lookup("java:global/com.war_1.0.0.SNAPSHOT/AdminService");
...
    }

        public synchronized void serviceChanged(ServiceEvent event) {
            switch (event.getType()) {
                case ServiceEvent.REGISTERED:
                    ServiceReference reference = event.getServiceReference();
                    adminService.installService(...);
                    break;
                default:
                    break;
            }
        }

I also tried to get EJB as OSGI service, with no success.
Is there a way to solve this problem? Maybe I shoudln't do it with ServiceListener?

thank you

UPD: I found kind of solution for this: add a startup singleton EJB that injects DAO service and adds a listener to OSGI, but it takes a bundleContext from static member from an activator. But it sometimes throws an IllegalStateException (bundleContext that is not active)


Solution

  • I found kind of solution for this: add a startup singleton EJB that injects DAO service and adds a listener to OSGI. But I'm still curious if there is a better approach