1

I'm trying to get my head around the fact that the spring IoC container holds just only one instance of an object that clients want to be injected with.

Let's define what is a singleton first

An object with mutable states that can only be reached outside of the stack, meaning it is residing in the method memory area (permanent generation space) of the JVM

If you annotation a method in spring with @Bean shown below:

@Bean
public Student getStudent() {
    return new Student();
}

The container will execute this and stores it in the container so that it can inject in constructors like this:

@Autowire
class StudentService() {

    public StudentService(Student s) {
        this.s = s;
    }
}

All fine and dandy. But, isn't this just an another form of a singleton pattern? I mean, sure you have to inject it in order to use it, but what if we have mutable states in the student that clients need and causes an unexpected to show up in another client? Is it common to not have mutable states in a bean and just have methods?

Thank you

Wim Deblauwe
  • 25,113
  • 20
  • 133
  • 211
Brendon Cheung
  • 995
  • 9
  • 29
  • Yeah, but you can easily mock a `Student` and create another `StudentService` instance with it for testing purposes. And `StudentService` does not care where the `Student` comes from, who creates it, etc. If you have mutability in your beans then you have done fucked up :D. – luk2302 Jun 03 '19 at 15:10
  • You can always change to another type: prototype, request, session, etc. Most beans that are singletons are interface based with other dependencies injected into their implementations (e.g. repository with pooled connection). Rod Johnson knew what he was doing. Objects like Student, that suggest method scope and instances, should be instantiated using new and not under the control of the Spring factory. – duffymo Jun 03 '19 at 15:22

1 Answers1

2

Basically, you should use singleton scope only for stateless beans. From Spring documentation:

[...] you should use the prototype scope for all beans that are stateful, while the singleton scope should be used for stateless beans.

When you obey this rule, situation you had described will never happen (i.e. shared mutable state).

So answering your question:

Is it common to not have mutable states in a bean and just have methods?

Yes, you should not hold the state inside beans with singleton scope.

Community
  • 1
  • 1
k13i
  • 4,011
  • 3
  • 35
  • 63