Injected Metadata in an entity listener is null

I’ve tried following the example given in this stackoverflow question to create an entity listener which, when one entity type is created, creates another entity of a different type associated with it. Here’s what I’ve got:

@Component("myapp_MyEntityListener")
public class MyEntityListener implements BeforeInsertEntityListener<MyEntity> {

    private Metadata metadata;

    public MyEntityListener() {
        System.out.println("MyEntityListener constructor");
    }

    @Inject 
    public void setMetadata(Metadata metadata) {
        System.out.println("MyEntityListener setMetadata " + (metadata == null ? "null" : "not null"));
        this.metadata = metadata;
    }

    @PostConstruct
    public void init() {
        System.out.println("MyEntityListener init - (metadata == null) = " + (metadata == null));
    }

    @Override
    public void onBeforeInsert(MyEntity entity, EntityManager entityManager) {
        System.out.println("MyEntityListener onBeforeInsert - (metadata == null) = " + (metadata == null));
        MyOtherEntity other = metadata.create(MyOtherEntity.class); // -> NPE
        other.setMyEntity(entity);
        entityManager.persist(other);
    }
}

During webapp deployment, I see the following in std out:

MyEntityListener constructor
MyEntityListener setMetadata not null
MyEntityListener init - (metadata == null) = false

So far so good. But when I try creating a new MyEntity via a standard editor page, I get the following in std out:

MyEntityListener constructor
MyEntityListener onBeforeInsert - (metadata == null) = true
java.lang.NullPointerException…

Any suggestions as to how I can fix this?

Hi David,

Could you please clarify if you created the listener by CUBA Studio or manually?

To resolve the issue we need to see how the listener is registered in MyEnity (see the

@Listeners

annotation).

Regards,

Aleksey

Hi Aleksey,

I created the listener in Studio, then edited the source in IntelliJ IDEA.

Thanks,

David

Ok, I see. Could you please zip and send over your project in the attachment, so we can have a look at it?

Hi Aleksey,

I’ll have to reproduce the error in a new project, without any commercially-sensitive stuff in it so I can send it to you. In the meantime, if it helps, I’ve checked the source for the “MyEntity” class and it has the @Listeners(“MyEntityListener”) annotation.

Kind regards,

David

David, seems there is no need to bother yourself with the project :).

Your listener is registered as

@Component("myapp_MyEntityListener")

, but declared in the entity as

@Listeners("MyEntityListener")

. Just try to change the declaration to

@Listeners("myapp_MyEntityListener")

and it should resolve the problem.

Please, let us know if it worked.

Regards.

1 Like

Ah! Perfect, that was the issue. Silly of me.

Many thanks for your help :slight_smile:

Welcome!