Monday, June 20, 2011

@ManagedBean inside OSGi bundle in GlassFish (3.1) - part 2

In previous post talked about utilizing javax.annotation.ManagedBean to create a ManagedBean in an OSGi bundle deployed in GlassFish.

A different (better) route would be to use CDI (Contexts and Dependency Injection) and utilize @Inject annotations instead of @Resource and @EJB for injecting the resources.

For this to work, there must be a 'beans.xml' file present. According to the docs:

An application that uses CDI must have a file named beans.xml. The file can be completely empty (it has content only in certain limited situations), but it must be present.

To make this possible in our bundles, added a 'META-INF' directory to the 'src' dir, with an empty 'beans.xml' file underneath.

Then in our bnd definition file (which builds the OSGi bundle for us), we define the resource to be included in our bundle:

Include-Resource:  META-INF/beans.xml=src/META-INF/beans.xml

With this in place, we no longer need to reference the 'com.sun.ejb.containers, com.sun.ejb.spi.io' libraries in our 'Import-Package' entry (since we are not using the ManagedBean annotation directly).

We can now replace all the @EJB and @Resource calls to @Inject.

@ManagedBean inside OSGi bundle in GlassFish (3.1)

Was struggling getting a @ManagedBean to be able compile correctly under GlassFish - needed to add the following packages to the Import-Package entry of the Manifest:

com.sun.ejb.containers,com.sun.ejb.spi.io

This allowed us to have a ManagedBean in the bundle.

For example - want to have a @Singleton class for some processing.

@Singleton
public class TestSingleton {
    public String testMySingleton() {
        return "This is a test from my singleton!";
    }
}

(this would be a javax.annotation.ManagedBean, not a Faces ManagedBean):

@ManagedBean
public class SingBean {
    @EJB
    private TestSingleton testSingleton;

and for testing purposes - within the MDB:

@MessageDriven(mappedName = "jms/MyQueue", activationConfig = {
    @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class ExtIncMDB {
    @Resource
    SingBean myBean;

Coming back...

Haven't written to this blog in a while - getting caught up with getting the project I have been working on working, but with some of the issues we are finding and the solutions to those issues, I really need to document them for future reference.

I have also been getting deeper into iOS and Android development, and have figured out some cool things there to start documenting and keeping around.

So major posts coming regarding Java EE 6/OSGi hybrid apps, iOS and Android development (as well as anything else I want to blab about just to keep record).

If others can find some of the snippets to help like I did searching around - would be great.