pjj
pjj

Reputation: 2135

How field injection breaks immutability

I read (for example here) that if I use field dependency injection then I cannot create immutable objects, but I don't understand how field dependency injection breaks the immutability, I can do something like below can create immutable SpringTest, no?

@Component
public final class SpringTest {

    @Autowired
    private Person person;

    // here I will have no setter methods exposing "person" object but will only have getter methods for "person" object, ensuring defensive copying etc...

}

UPDATE: Please note that my question is specifically about field injection breaking the immutability, so I want to know how my above code snippet (changed since my original questions, thanks to @Andy and others for correcting it) is breaking the immutability, I think it is not, so I think this answer is wrong about immutability with field injection.

Upvotes: 5

Views: 1171

Answers (2)

Elyor Murodov
Elyor Murodov

Reputation: 1028

Immutable object shouldn't be possible to modify after it's constructed.

Spring injects autowired private field after the object has been constructed. It's contradicting the immutability principle, so immutability is therefore broken.

But, in case of Autowiring via constructor injection, we are not breaking immutability as far as the field is declared private final, since this sets the value to the field only once and during object construction.

Additionally, if the Person object is mutable and you have a getter for it, then it's clearly breaking the immutability of SpringTest as well.

Upvotes: 1

Andy Turner
Andy Turner

Reputation: 140534

It's mutable because you can reassign the field yourself (or from any other class in the same package).

Merely intending not to reassign a field is not the same as not being able to do so.

Upvotes: 4

Related Questions