How do I choose the right scope for a bean?

Asked

Viewed 367 times

1

From what I’ve been studying, I know there are several scopes for Beans:

@RequestScoped
@ViewScoped
@FlowScoped
@SessionScoped
@ApplicationScoped

What is the function of each? How should I correctly choose the scope of my bean?

1 answer

2


The difference is basically in the duration of each.

@RequestScoped It is born and dies after each request, no state is saved. It should be used on pages that only send data for viewing and have no subsequent action that depends on this data in the backend, for example, listings;

@ViewScoped It is born after each page opening, and dies as soon as the one change in the context URL happens. Should be used in cases where editing of some data happens and the Beans in the backend should stay alive so they can be saved later;

@FlowScoped It’s basically the same as @ViewScoped but it does not end with the page exchange, you can define a group of pages that share the same scope, and end up at a certain point. Can be used for registrations that last for more than one page for example;

@SessionScoped It is born as soon as a Session is established with the customer and the bean in question is ordered, it dies as soon as the Session is finished. This bean has a very long duration and should not be used in most scenarios. Should be used only to store user session information that should last longer;

@ApplicationScoped It is born as soon as it is requested for the first time in the application, lasts while it is alive and is shared among the various customers. It should be used to do things in the context of the application, such as storing a number of logged in clients (it’s a dumb example, but I just thought of this now);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.