Hello. Can I extend the standard cuba class UserEntityListener to add behavior to the event onBeforeInsert?
I solved it with the help of the following class:
import com.haulmont.cuba.core.EntityManager;
import com.haulmont.cuba.security.entity.User;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
@Component
public class UserEntityListenerPostProcessor implements BeanPostProcessor {
private List<BeforeInsertUserListener> beforeInsertUserListeners = new ArrayList<>();
private List<AfterDeleteUserListener> afterDeleteUserListeners = new ArrayList<>();
public void addBeforeInsertUserListener(BeforeInsertUserListener listener){
beforeInsertUserListeners.add(listener);
}
public void addAfterDeleteUserListener(AfterDeleteUserListener listener){
afterDeleteUserListeners.add(listener);
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if ("cuba_UserEntityListener".equals(beanName)){
return Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(), (proxy, method, args) -> {
if ("onBeforeInsert".equals(method.getName())){
beforeInsertUserListeners.forEach(l -> {
try {
l.onBeforeInsert((User)args[0], (EntityManager)args[1]);
} catch (Exception e){}
});
}
Object returnValue = method.invoke(bean, args);
if ("onAfterDelete".equals(method.getName())){
afterDeleteUserListeners.forEach(l -> {
try {
l.onAfterDelete((User)args[0], (Connection)args[1]);
} catch (Exception e){}
});
}
return returnValue;
});
}
return bean;
}
public interface BeforeInsertUserListener {
void onBeforeInsert(User entity, EntityManager entityManager);
}
public interface AfterDeleteUserListener {
void onAfterDelete(User entity, Connection connection);
}
}
I would recommend a simpler approach: to register an additional listener for the User
entity. See an example in the cookbook.