简体   繁体   English

现场注入如何打破不变性

[英]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? 我读(例如这里 )如果我使用字段依赖注入然后我不能创建不可变对象,但我不明白字段依赖注入如何打破不变性,我可以做下面的事情可以创建不可变的SpringTest ,不?

@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. 更新:请注意我的问题是关于字段注入打破不变性,所以我想知道我的上面的代码片段(自我原来的问题以来改变,感谢@Andy和其他人纠正它)打破了不变性,我认为事实并非如此,所以我认为这个答案对于场注射的不变性是错误的。

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. 仅仅打算不重新分配一个领域与不能这样做是不一样的。

Immutable object shouldn't be possible to modify after it's constructed. 不可变对象在构造之后不应该被修改。

Spring injects autowired private field after the object has been constructed. Spring在构造对象后注入自动装配的私有字段。 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. 但是,在通过构造函数注入进行自动装配的情况下,只要字段被声明为私有final,我们就不会破坏不变性,因为这只将值设置为字段一次并且在对象构造期间。

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. 另外,如果Person对象是可变的并且你有一个getter,那么它显然也打破了SpringTest的不变性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM