A developer writes two session beans which cooperate. The first session bean, ShoppingCart, collects orders and is implemented as a stateful session bean. The second session bean, CalculateDiscount, is implemented as a stateless session bean and runs on a different server. ShoppingCart contains the method getTotalPrice, which calculates the total price of the order in the ShoppingCart, including discounts. Discounts are calculated by CalculateDiscounts using the information on the Shopping
Cart bean, combined with data from a database. Which scenario can accomplish this?
- The CalculateDiscount offers a method calculate which is invoked by the ShoppingCart bean passing the "this" reference
- The CalculateDiscount offers a method calculate which is invoked by the ShoppingCart bean. CalculateDiscount accesses the ShoppingCart instance by JNDI lookup.
- The CalculateDiscount offers a method calculate which is invoked by hte ShoppingCart bean passing its reference obtained from the SessionContext.getBusinessObject method
- The CalculateDiscount offers a method calculate which is invoked by the ShoppingCart bean. CalculateDiscount accesses the state of ShoppingCart by dependency injection.
Para hacer esto más llevadero, comencemos por la respuesta, que es la tercera.
El método SessionContext.getBusinessObject() nos devuelve una referencia al EJB actual que puede ser invocada por otros clientes, como el bean CalculateDiscount de la pregunta. Esta referencia sería el equivalente EJB de la sentencia Java "this". getBusinessObject recibe como parámetro un objeto Class, que debe ser una de las interfaces (remota o local) del bean, de modo que el contenedor sepa si crear una referencia local o remota del EJB actual. El método getBusinessObject permite a la instancia bean obtener su propia referencia EJB, que puede luego pasar a otros beans (como CalculateDiscount ). Aquí un ejemplito:
@Stateless
public class A_bean implements A_BeanRemote{
@Resource
private SessionContext context;
public void someMethod(){
B_BeanRemote b = ... // referencia remote a B_bean
A_BeanRemote mySelf = getBusinessObject(A_BeanRemote.class)
b.aMethod(mySelf);
}
...
}
Es ilegal para una instancia bean pasarle la referencia "this" a otro bean; por el contrario, debe pasarle una referencia local o remota del EJB, que el bean puede obtener de SessionContext.
Pregunta tomada de ExamWorx
Publicar un comentario