• Post Reply Bookmark Topic Watch Topic
  • New Topic

Calling a Injected EJB in child class using @EJB on GlassFish result in a NullPointerException

 
Jose Ortuno
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Hi there,

New to EJB 3 and I trying to access a remote EJB from a very simple EE Client deployed on GlassFish 3.
I created a mock bean with a very simple method. It works as long as I inject the EJB using @EJB anotation in the main class. Moving, forward I tried to create a JFrame to prompt for some information, so I can pass it to the remote bean.
When y tried to inject the same EJB in the second class (The form) the reference is always NULL causing a NULL pointer exception.

Here is the relevant code:

Client Class:
public class Main {

@EJB
public static MockBeanRemote mockBean; // Bean is injected


public static void main(String[] args) {

System.out.println( mockBean.tryMe() ) ; // Work just fine displaying a console message

}
}


***** Second Approach ****
Cliente Class:
public class Main {

// @EJB
// public static MockBeanRemote mockBean; <<<< remove injection


public static void main(String[] args) {

new MyFrame(); // Display the Form

}
}


Form Class:

public class MyFrame extends javax.swing.JFrame {

@EJB
public static MockBeanRemote mockBean; // <<<<<< Inject remote bean just like before

...

/** Creates new form and components */
public MyMain() {
initComponents();
}

.....

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // event is performed
...
// try to call remote method
mockBean.tryMe(); // At this point mockBean is NULL ..! Therefore NullPointerEception is thrown
}

...
}

**************

As a workaround I decide to move injection back to main Class, declare it as public static mockBean and call the method using Main.mockBean() and it works again ......... I know it is a bad approach.
Please let me know what is happening underneath so I can do the right think.

Thanks folks in advance!

Jose
 
Jaikiran Pai
Sheriff
Posts: 10447
227
IntelliJ IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jose Ortuno wrote:

As a workaround I decide to move injection back to main Class, declare it as public static mockBean and call the method using Main.mockBean() and it works again ......... I know it is a bad approach.


In this case, it's not a bad approach. Infact, it is the only approach. Application clients only support injection in the main class' static fields.

You can however use JNDI lookup instead of injection in other classes if you want to.
 
Jose Ortuno
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Jaikiran!

Now it make sense, I will implement your suggestion by using JNDI. I absolutely need to get deeper on EJB 3. :-)

Cheers.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!