2

After an entity is persisted, I want to execute a Bean, which sends a registration Mail to the newly registered user. I want to do this with a Listener class. I did the following:

  1. Annotated the Entity with @EntityListener (UserListener.class)
  2. Created the Listener and annotated it with @Stateless

Here is the code of the listener: ( the system.out.println part is just for testing purposes)

@Stateless
public class UserListener {

    @Inject
    private MailSenderController mailSenderController;

    @PostPersist
    void onPostPersist(User user) throws AddressException{
       System.out.println("PostPersist");
       System.out.println("Username: " + user.getUsername());
       mailSenderController.sendRegistrationMail(user);
   }
}

The MailSenderController is a @RequestScoped annotated Bean.

If I execute the code, I get a NullPointerException. If I remove mailSenderController.sendRegistrationMail(user), the code works fine.

I think the onPostPersist gets executed before the MailSenderController gets injected and this causes the NullPointerException.

Can someone help me out with this problem?

MWiesner
  • 8,868
  • 11
  • 36
  • 70
Rallenaldo
  • 107
  • 8

2 Answers2

1

I am guessing that MailSenderController is not the entry point of your user registration entry point. If yes then MailSenderController is always going to be NULL. Considering the MailSenderController has request scope, DI framework would only instantiate the controller processing HTTP request for sending mail.

From design point of view its not good to call your controller directly from DAO layer classes. I think you need to create a new managed bean (single instance) MailSenderService and then inject the new service instead of accessing a request scoped controller.

Suken Shah
  • 1,622
  • 14
  • 20
  • MailSenderController is not the entry point for the registration process. Its a UserListController, which is SessionScoped. Like I read in a Java EE Book, I should delegate to different controlers and fire an Event if I want to persist something. A stateless Service Bean does the persisting in the end. I searched the web for more problems like mine and I found out, that Glassfish seems to have problems with Dependency Injection into Bean. Maybe this is the problem. EclipseLink has a bugfix for it. Haven´t found a fix for Hibernate until now. – Rallenaldo Dec 09 '15 at 20:00
0

just add @Named annotation to MailSenderController

  • The MailSenderController is annotated with Named and RequestScoped. Didn´t mention it in the question. My fault. – Rallenaldo Dec 08 '15 at 19:10