tags:

views:

65

answers:

4

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.

A: 

Try doing your initialization within a static block. This will run once when the classloader loads the class.

static { System.out.println("static"); }
brianegge
A: 

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
    }

}
Valentin Jacquemin
This fires for each EJB instance, and there may not be an instance created until the first business request comes along.
djna
+1  A: 

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.

djna
Do you know if jboss provide extensions to allow this?Thanks.
David
I don't have experience of JBoss, and a quick google hasn't revealed anything. So, sorry I can't help with that.
djna
Didn't look too closely, but Jboss has this.http://www.jboss.org/file-access/default/members/jbossejb3/freezone/docs/tutorial/1.0.7/html/Service_POJOs.html
TJ
A: 

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)?

Pascal Thivent