开发者

Java CDI & Observer issue - When the listener method is invoked, dependencies are null

Issue: When the listen method is invoked on ContentViewLog, the log and entity manager are null.

BlogDetailBean (A bean used on a JSF2 page)

@Named
@RequestScoped
public class BlogDetailBean {

    @Inject
    private BlogService blogService;

    @Inject
    Event<ContentViewEvent> blogViewEvent;

    ...

    public String loadEntry(){
      this.blogViewEvent.fire(new ContentViewEvent(this.entry));
    }

    ...

}

ContentViewLog (A bean that listens for ContentViewEvents)

@Stateless
@Named
public class ContentViewLog {

    @Inject
    private Logger log;

    @Inject
    @DataRepository
    private EntityManager em;


    private void listen(@Observes final ContentViewEvent e) {
        this.log.info("Content View Event: " + e.toString());
        final LoggedContentView lcv = new LoggedContentView(e);
        this.em.persist(lcv);
    }

    public Long getTotalViews() {
        final Long result = (Long) this.em.createNamedQuery(
            "loggedContentView.countAll")开发者_运维技巧.getSingleResult();
        return result;
}

    ...

}

As an aside, what's particularly confusing is that ContentViewLog's other methods, such as getTotalViews, work when used from other beans (though, in those cases, I'm not using CDI events.)

FYI - there are 2 beans not shown above that use @Produces to supply the Logger and EntityManager instances.


Just a shot in the dark, since I agree we need to know what CDI and container you're using, but have you tried making the observer method public instead of private? I have a feeling that proxying won't work correctly in this case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜