Spring instantiation of prototype scoped beans under the hood
java, spring
Solution
Like any other bean: using the constructor annotated with @Autowired, or the default one if there isn't any (or a factory method if one is defined).
What you heard is wrong. Most objects are not cloneable, so it would only get an exception by doing that. And it would make no sense since
- it wouldn't be able to create the first instance
- all the instances would be the same as the first one, which is clearly not what is wanted.
Problem
Spring defines different scopes of bean definitions, one being the prototype scope, which gives a new instance at every lookup. I have two doubts regarding it.. - Under the hood, how spring creates a new instance ? - I have heard, it uses clone() method to create a new instance, if yes, then why and if it uses clone to give a new instance, then what happens to the state of the cloned object, as clone will copy the state also ?