spring and interfaces

后端 未结 9 793
无人及你
无人及你 2020-12-08 14:45

I read all over the place about how Spring encourages you to use interfaces in your code. I don\'t see it. There is no notion of interface in your spring xml configuration.

9条回答
  •  隐瞒了意图╮
    2020-12-08 15:18

    If you don't use interfaces you risk an autowiring failure: Sometime Spring creates a Proxy class for a Bean. This Proxy class is not a child class of the service implementation but it re-implements all of its interfaces. Spring will try to autowire instances of this Bean, however this Proxy class is incompatible with the Bean class. So declaring a field with Bean class can lead to "unsafe field assignement" exceptions.

    You cannot reasonably know when Spring is going to Proxy a service (nor should you), so to protect yourself against those surprises, your best move is to declare an interface and use this interface when declaring autowired fields.

提交回复
热议问题