开发者

JavaEE and CDI: Understanding @Observes

开发者 https://www.devze.com 2023-03-19 07:41 出处:网络
I have the archetype org.jboss.weld.archetypes:jboss-javaee6-webapp:1.0.1.CR2 and I try to understand the class MemberListProducer:

I have the archetype org.jboss.weld.archetypes:jboss-javaee6-webapp:1.0.1.CR2 and I try to understand the class MemberListProducer:

@RequestScoped
public class MemberListProducer
{
  @Inject @MemberRepository private EntityManager em;

  private List<Member> members;
  @Produces @Named public List<Member> getMembers() {return members;}

  public void onMemberListChanged(@Observes(notifyObserver = Reception.IF_EXISTS)
                                  final Member member){
    retrieveAllMembersOrderedByName();
  }

  @PostConstruct
  public void retrieveAllMembersOrderedByName()
  {
    //Criteria Query to fetch all members
    members = em.createQuery(criteria).getResultList();
  }
}

The observer is invoked from another class with memberEventSrc.fire(开发者_如何转开发newMember);, this seems clear: Once fired, the MemberListProducer updates the list of members.

But I don't understand why this is done in a @RequestScoped Bean. In my understanding the method retrieveAllMembersOrderedByName is anyway called by each request. Should this @Observes not be better placed in a @ViewScoped or @SessionScoped Bean? Does it have an effect in this case at all?


The use of @Observes there is more of an example than a real, practical use case. Consider the possibility of members changing before you render your response. I don't think the website would work correctly if you removed it. Think about it like this:

When the request starts, the list of members is created and it contains all the members up to the moment of creation of this request scoped bean. Later, you persist a new member, so this list needs to be updated to render the response.

You think correctly when you say that the list is built for each request, however this happens at the beginning. After you add a member, you need to refresh it, don't you? If this method weren't there, the response would be outdated (you'd render the list you had before you persisted the new member), and you would need one extra post or get to fetch the new list of members.

@Observes decouples listeners and event sources much like the observer pattern. So if the @Observes isn't there, you would need to explicitly add the new member to the list so that the response is correct.

I hope I understood your question correctly.


It's request scoped because it stores a list of members per request. If you need this list to be stored per-session, then change it.

But it looks wrong - you are discarding the member arguments of the observer method.

0

精彩评论

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

关注公众号