Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Simplify enterprise Java development with EJB 3.0, Part 1

Use annotations to develop POJO services

  • Print
  • Feedback

Page 6 of 6

 @Stateless
@SecurityDomain("other")
public class CalculatorBean implements Calculator {

@RolesAllowed({"AdminUser"}) public void addFund (String name, double growthrate) { // ... ... }

@RolesAllowed({"AdminUser"}) public void addInvestor (String name, int start, int end) { // ... ... }

@PermitAll public Collection <Fund> getFunds () { // ... ... } // ... ...

@RolesAllowed({"RegularUser"}) public double calculate (int fundId, int investorId, double saving) { // ... ... } }


Generic interceptors

Both transaction and security services can be considered runtime interceptors managed by the container. The container intercepts the method calls from the EJB stub and applies transaction context or security constraints around the calls.

In EJB 3.0, you can extend the container services by writing your own interceptors. Using the @AroundInvoke annotation, you can specify any bean method as the interceptor method that will execute before and after any other bean method runs. In the following example, the log() method is the interceptor that profiles and logs the execution time of other bean methods:

 @Stateful
public class CalculatorBean implements Calculator {

// Bean methods that are to be intercepted by "log()" // ... ... @AroundInvoke public Object log (InvocationContext ctx) throws Exception {

String className = ctx.getBean().getClass().getName(); String methodName = ctx.getMethod().getName(); String target = className + "." + methodName + "()";

long start = System.currentTimeMillis(); System.out.println ("Invoking " + target); try { return ctx.proceed(); } catch(Exception e) { throw e; } finally { System.out.println("Exiting " + target);

cal.setTrace(cal.getTrace() + " " + "Exiting " + target); long time = System.currentTimeMillis() - start; System.out.println("This method takes " + time + "ms to execute"); } } }


What's next?

In Part 1 of this series, I discussed the general POJO-based programming model for EJB 3.0 and how to develop loosely coupled service objects in EJB 3.0. In Part 2, I will discuss another major aspect of EJB 3.0: managed POJO persistence. Stay tuned.

About the author

Dr. Michael Yuan works for JBoss. He specializes in end-to-end enterprise solutions. He is the author of three books, Nokia Smartphone Hacks, Enterprise J2ME, and Nokia Series: Developing Scalable Series 40 Applications. Yuan received a Ph.D. degree from the University of Texas at Austin.

Read more about Enterprise Java in JavaWorld's Enterprise Java section.

  • Print
  • Feedback

Resources