2

I have read different articles on using @Stateful and @SessionScoped annonations and their differences including this post. From a definition point, @sessionScoped is used when a session is needed/created between client/web tier, while @Stateful is needed in Bussiness Logic layer. But I still do not get a hold of the real differences when it comes to implementing them. Here is a simple example

@Named
@SessionScoped
ShoppingCartUIBean {

 @inject 
  shoppingCart cart;
  // more code
}

@Stateful
ShoppingCart {

//business logic of adding/updating/deleting cart items
}
  1. How is the Http session maintained by @SessionScoped bean between a given user and server? That is, if I have a shopping cart opened in different computers, I should be able to see my shopping cart, which is associated with my user profile. How is this established?
  2. what happens if I switch the two annonations on the above beans? will it have any effect? (sorry this might sound stupid. I am getting into Java EE world, so I want to get basics correct).
  3. According to this great post on Differences : @SessionScoped vs @Stateful and @ApplicationScoped vs @Singleton, @Stateful beans are hardly used in web applications. Is there a case where @Stateful is absolutely necessary?
  4. ON a related note: is it legal to inject a @stateful bean into @ApplicatonScoped bean? This would mean entire the application has a single @stateful bean and all clients uses the same instance of one stateful bean via proxy. (Just as is demonstrated here, not to inject @Stateful in servlets EJB example for stateless and stateful beans difference).

Thanks.

Community
  • 1
  • 1
brain storm
  • 30,124
  • 69
  • 225
  • 393

1 Answers1

0

I will try to answer some of your question with my best.

Ad.1 @SessionScoped is about browser session, so you won't see the same session on different computers(or browsers).

Ad.2 You can't think about those two as the same components only because the same scope. Fundamental think is that EJB and JSF beans rely on different architecture layers. EJB beans should implement business logic while jsf beans should maintain forms and other ui components.

Ad.3 @Stateful beans are very useful in seam framework. Using those beans and extended persistance context is solution for lazy initialization error(probably that's a reason why seam creators use those beans). I prefer Stateless beans according to performance but it hardly depends on use case(whether you want keep state or not).

Ad.4 In general you shouldn't inject "less scope" beans to "more scope" beans. Application scope will exist while session may be destroyed and what this application bean should have in place of destroyed session bean?

Correct me if i'am wrong with any of this answers.

  • 1
    I think your 4th point is wrong. That is a single session bean always for all different sessions. The single session will never be destroyed.. – brain storm Oct 09 '14 at 18:02