CDI injection in EntityListeners

≯℡__Kan透↙ 提交于 2019-11-27 19:20:34

问题


Since JPA 2.0 does not support injection into EntityListener (JPA 2.1 will), decided to use JNDI lookup to get the BeanManager and through it get the logged in user. I defined an EntityListener similar to this:

public class MyEntityListener {

    public static BeanManager getBeanManager() {
        try {
            InitialContext initialContext = new InitialContext();
            return (BeanManager) initialContext.lookup("java:comp/BeanManager");
        } catch (NamingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public Object getBeanByName(String name) {
        BeanManager bm = getBeanManager();
        Bean bean = bm.getBeans(name).iterator().next();
        CreationalContext ctx = bm.createCreationalContext(bean);
        return bm.getReference(bean, bean.getClass(), ctx);
    }

    @PrePersist
    @PreUpdate
    public void onPreInsertOrUpdate(MyEntity entity) {
        User loggedInUser = (User) getBeanByName("loggedInUser");
        entity.setUpdatedUser(loggedInUser);
        entity.setUpdatedTimestamp(new Date());
    }
}

User is managed in session scope as:

@SessionScoped
public class UserManager implements Serializable {

    private User loggedInUser;

    @Produces
    @Named("loggedInUser")
    public User getLoggedInUser() {
        return loggedInUser;
    }

    // Set the logged in user after successfully login action
}

I want to know is there any disadvantages or points to pay attention of this approach. Performance throughput? What happens when there are multiple logged in users updating entities concurrently in their own scopes?
Hibernate JPA 2.0
Seam Weld CDI
Glassfish 3.1.2


回答1:


Your approach is correct.

Performance throughput?

IMHO no need to worry - JPA 2.1 will use an equivalent mechanism. But make sure to write a realistic test to be on the safe side.

What happens when there are multiple logged in users updating entities concurrently in their own scopes?

All (non-dependend-scoped) bean references are proxied internally. The underlaying CDI-implementation has to guarantee the correct resolution.



来源:https://stackoverflow.com/questions/10765508/cdi-injection-in-entitylisteners

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!