Search This Blog


Sunday, February 12, 2012

Glassfish: How to create lookups resources (simple & JavaBean Object)

It is a good idea to make your code modular and maintainable (less code modifications) when depending on resources.

To create a resource in application server so that all deployed applications can look them up, and make your application is loosely coupled on the resource it lookups, and be more dynamic.

The resource types can be object, string, boolean, number, or any custom java bean types.

In Glassfish 3+ CLI (Command Line Interface), they are created and managed with a set of generic commands:

asadmin create-custom-resource ...
asadmin list-custom-resources ...
asadmin delete-custom-resource ...
asadmin get 'resources.custom-resource.*'
asadmin set ...

GlassFish admin console provides GUI (Graphical User Interface) way of doing things but I found using CLI (Command line Interface) is a lot faster.

For example:

To look up the custom resource created above:

An easier way to obtain these resources is through @Resource injection:

You can view all attributes and properties of a custom resource with asadmin get command:

To update the value of a custom resource with asadmin set command:

In addition to the above simple value custom resources, GlassFish also provides decent support for POJO JavaBean custom resources.

The steps are very similar to String and primitive custom resources, except that you will need to provide your resource impl class and use a different GlassFish factory class.

For example, suppose we need to implement a Book class:

Compile it and copy Book.class to GlassFish domain lib directory, restart the domain, and create a custom resource of type Book:

To list the attributes and properties of the newly-created resource with GlassFish asadmin get command:

To update the pages property of the resource with asadmin set command:

To look up the custom resource, resource/book, from a webapp, or Java EE application:

You can inject it into Java EE web component or EJB component class such as servlet, filter, web listener, interceptor, or EJB bean class:

A Java SE remote client can also look up the resource:

The following shows how to build and run the remote JNDI client, and the output:

Note that both TestLookup.class and Book.class are in current directory and therefore are in the client classpath. Person class also implements to make remote access possible.