Domanda

I am new to spring mvc web development. I have one query. Suppose we are having different service classes. So do we have one instance of those classes per request OR only single instance of that class gets create. Actually i want to use instance variables , so with each request new instance will get created or it will be like singleton type of behavior. Hopefully i am able to explain my question.

È stato utile?

Soluzione

you can have either, the default is a singleton - one instance. But this can be changed using bean scope.

obligatory link to offical docs correct chapter

(personally never needed to use anything other singleton)

Altri suggerimenti

If you have not defined any scope explicitly, it will be singleton by default, singleton means there will be one object per spring container, for your context, one object for all your request threads. In case of singleton scope, be cautious while using member variables, because thread safety comes into picture.

If you are modifying state of a member variable inside your singleton scoped bean, you need to write thread safe code because multiple threads are accessing your member variable and a race condition may occur.

Moreover, you can define other scopes too using @Scope at the class level(i.e above @Component) or at method level above @Bean annotations.

Generally, we keep using the default scope (i.e singleton scope), this way spring container also does not waste time in creating the new object of the bean asked for, though it would be a little overhead creating an object on each request thread.

If you want a new object on every bean injection, you can have prototype scope for that bean.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top