Java EE Custom Annotation Lookup

Thinking about plugins in a webapp, I wanted a way to have an interface that my code would call when certain things happened.

As a POC, I created an annotation and interface to run after an action completes. First we create the interface:

We will call the afterComplete() method when the action is complete. For simplicity, it just takes a String.

Now, we need an annotation so we can look it up in the container’s context:

This is a simple annotation that allows us to locate each bean that is annotated with it, and get the implementing class. If we create the EJB we want to discover like this, we can easily find it. This is a simple class that prints a log message:

The following code will find all the EJBs that have our @AfterComplete annotation and call their afterComplete(…) method with a simple String:

We can use this method in a Servlet, REST endpoint, or whatever else we want to create callbacks for different methods. There is an example Servlet and 2 beans that have a discover-able annotation at https://github.com/mikebski/ejb-custom-annotations that is a Maven project that can be used for a demonstration.

Check it out and run mvn package to generate a war file, then deploy it and go to:

http://localhost:8080/ejb-custom-annotations-1.0/ to see the output. The output should be:

class net.mikeski.ejb_annotations.AfterCompletePrinterclass net.mikeski.ejb_annotations.AfterCompleteErrPrinter

and your console should have 2 log messages like this:

18:45:51,937 INFO [stdout] (default task-43) After complete printer: After complete called on Proxy for view class: net.mikeski.ejb_annotations.IAfterComplete of EJB: AfterCompletePrinter

18:45:51,939 ERROR [stderr] (default task-43) After complete called on Proxy for view class: net.mikeski.ejb_annotations.IAfterComplete of EJB: AfterCompleteErrPrinter

Leave a Reply

Your email address will not be published. Required fields are marked *