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?