@Autowire strange problem

前端 未结 3 1189
借酒劲吻你
借酒劲吻你 2020-12-11 01:07

I have a strange behaviour when autowiring

I have a similar code like this one, and it works

@Controller
public class Class1 {
    @Autowired
    pri         


        
3条回答
  •  暖寄归人
    2020-12-11 01:23

    The Transactional annotation instructs Spring to generate proxy objects around the annotated beans, to implement the transactional semantics. The generated proxy will implement the same interfaces as the target bean. So if your target bean implements IServiceReference, then so will the generated proxy.

    If the target bean has no implemented interfaces, then the generated proxy will instead be a subclass of the target bean type.

    In your original example, the transactional proxy will be a subclass of Class2, because Class2 implemented no interfaces. When you changed Class2 to implement IServiceReference, the generated proxy no longer extended Class2, and instead implemented IServiceReference. This caused your ClassCastException.

    The best approach to this situation is to remove the reference from Class1 to Class2, and instead talk to Class2 purely through its interfaces. Class2 can implement as many interfaces as you like, the proxy will implement all of them.

    You can force Spring to generate subclass proxies regardless of the interfaces, but it's additional complexity, and I'd recommend against it.

提交回复
热议问题