• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to get EJB bean instance using a factory.  RSS feed

 
Rahul Babbar
Ranch Hand
Posts: 210
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am trying to look in to a code of EJB 2, where everywhere the lookup into initialContext for the jndi name of the ejb is done.
something like...
XXXHome home = (XXXHome) PortableRemoteObject.narrow(ctx.lookup(XXXHome.JNDI_NAME),
XXXHome.class);
return home.create();

This gives me bean instance on which i can use.....

However i wanted to use a general method in a certain class which will return me the required bean instance, if i pass the Jndi name and the Home class...so that i can use that method to get any instance of the bean..
So, i tried to write something like this...passing XXXHome.JNDI_NAME and XXXHome.class for getting the bean.

public static Object getEJB(String jndiName, Class clazz){
try {
InitialContext ctx = new InitialContext();
//EJBHome home = (EJBHome)PortableRemoteObject.narrow(ctx.lookup(jndiName), clazz);
//return home.create();

} catch (NamingException e)
{
// do something
}
}

The problem is i dont know which will be the object of home interface that will be returned by PortableRemoteObject.narrow(ctx.lookup(jndiName), clazz), or even what will be the type of object..so, i cannot call create() on the returned object to get the bean instance.
So, probably all my interfaces homes like XXXHome should extend some YYYHome(which should have the create method also).
Note that EJBHome does not have create() method so, i cannot use EJBHome in such case,(that is why i have commented out the line).
So, if i can have some interface CustomEJBHome extend EJBHome such that it adds create() method, so that i can somehow(if possible) make my XXXHome and YYYHome extend CustomEJBHome and not EJBHome, i can get all the EJBs which i want in the following way.


public static Object getEJB(String jndiName, Class clazz){
try {
InitialContext ctx = new InitialContext();
CustomEJBHome home = (CustomEJBHome )PortableRemoteObject.narrow(ctx.lookup(jndiName), clazz);
return home.create();

} catch (NamingException e)
{
// do something
}
}

but is there some way to make sure that all my homeinterfaces extend my CustomEJBHome (which has create() method in addition to EJBHome) and not EJBHome, so that i can fulfill the above requirement.

P.S. I am quite a novice in EJBs, so excuse me if i have used the wrong terminology somewhere or have missed an important/easy concept, but i hope i am able to make my point clear.
 
J J Wright
Ranch Hand
Posts: 254
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use Service Locator - http://java.sun.com/blueprints/corej2eepatterns/Patterns/ServiceLocator.html
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!