Friday, 3 June 2011

EJB3 Stateless Session Bean Annotations

Creating a Stateless EJB using EJB3’s annotations is very simple. Just in case you can’t remember this is how to annotate your java code to create a simple User bean.

Firstly, you need to create a remote interface using the @Remote annotation.

@Remote
public interface User {

 
String getUserName(String userID);

  String getUserID
(String name);

 
boolean userExists(String id);
}

Next, if required, create your local interface using the @Local annotation.

@Local
public interface UserLocal {

 
String getUserName(String userID);

  String getUserID
(String name);

 
boolean userExists(String id);
}

You may have noticed that I said ‘if required’ above. The reason for this is that the @Remote and @Local interfaces are optional. You MUST have one or both of the above depending upon what you want to do with the bean.

The last part of creating a stateless session bean is to mark your implementation bean with the @Stateless annotation. If you’re using a Weblogic server remember to add the name and mappedName attributes.

@Stateless(name = "DummyUser", mappedName = "DummyUser")
public class UserBean implements User, UserLocal {

 
/**
   *
@return Return the user's name for the given ID.
   */
 
public String getUserName(String userId) {

   
return "Fred Jones";
 
}

 
/**
   *
@return Return the users ID code for the user's name.
   */
 
public String getUserID(String userName) {

   
return "12s34F";
 
}

 
/**
   *
@return True. The user always exists.
   */
 
@Override
 
public boolean userExists(String id) {

   
return true;
 
}
}

No comments: