Hello, I want to call to a method from an EJB in the same instant in which one deploys itself, without using a servlet.
Thanks.
David.
Hello, I want to call to a method from an EJB in the same instant in which one deploys itself, without using a servlet.
Thanks.
David.
Try doing your initialization within a static block. This will run once when the classloader loads the class.
static { System.out.println("static"); }
The PostConstruct hook is right for that.
Find more info on about PostConstruct here:
Let's finish with a quick example:
@Stateless
public class TestEJB implements MyEJBInterface{
@PostConstruct
public void doThatAfterInitialization() {
//put your code here to be executed after creation and initialization of your bean
}
}
There seems to be no life-cycle methods defined by the EJB spec for this purpose. Individual vendors may provide extensions to allow this. For example Startup Beans in WebSphere would be a place to put the invocation logic you want.
Using techniques such as a static method seem slightly dangerous in that we don't know whether all dependency injection is complete before that static method fires, and hence whether you can safely use the business methods of the EJB.
Persoanlly, if I needed to be portable I would bite the bullet and use a servlet. It costs very little.
Static initializer blocks are technically not illegal in EJB but they are used to execute code before any constructor (which might be a problem) when instantiating a class. They are typically used to initialize static fields which may be illegal in EJB if they are not read only. So, what about using ejbCreate()
, setSessionContext()
or setEntityContext()
methods instead (not even sure this would be appropriate without more details on the problem you are trying to solve)?