ybondar
ybondar

Reputation: 409

Spring beans scopes in web application. Best practices

I have some doubts about this topic. In our application for most Spring beans(dao`s, services and controllers) we use "request" scope. This approach allows us decrease memory usage and create stateless tiers. But in other hand we loose perfomance on every request on Spring context initializing. I think about creation some beans, e.g. DAO layer, in "singleton" or "prototype" scope.

What techniques do you use in your applications? Maybe exist some advices for designing Spring Web application beans scopes?

Upvotes: 7

Views: 9325

Answers (2)

psabbate
psabbate

Reputation: 777

Singleton: Scopes a single bean definition to a single object instance per Spring IoC container.

Prototype: Scopes a single bean definition to any number of object instances.

Request: Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

Session: Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

Global Session: Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

Besides this information, you should mark your DAO as @Repository, your controller with @Controller and your Service Layer with @Service.

Service, Repository and Controller Discussion

Upvotes: 5

ramsinb
ramsinb

Reputation: 2005

The general rule that I tend to use when deciding is the following:

Long Lived State

This is when state needs to be preserved over multiple requests (http). In this case it makes sense to store in a session scope.

Short Lived State

When you need to persist state for any given request. Perhaps you are implementing something like a backing bean for a form. In this situation I use a request scope.

No State

This is the singleton and is generated by default from spring. Unless I have a specific requirement for state this is the option that I generally stick with for all beans. Of course it's more performant too, as the bean is created only once and used by all.

In your case, your DAO & Services should be stateless (if they are not rethink how you have implements them) and therefore should be singletons. The controllers should be singleton again however the question for you is do they contain state?. I wouldn't worry too much about memory consumption, remember the root of all evil is premature optimisation. Stick with the best practise and if that doesn't work then fix it.

Upvotes: 16

Related Questions