@Autowire strange problem

前端 未结 3 1200
借酒劲吻你
借酒劲吻你 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:22

    The problem is that your Class1 needs a reference to IServiceReference and not the concrete reference of Class2

    @Controller
    public class Class1 {
    @Autowired
    private IServiceReference object2;
        ...
    }
    

    The reason this is that Spring is creating a dynamic proxy for classes that you marked @Transactional. Thus when Class2 is created its wrapped in a Proxy object that is obviously not of type Class2 but is of type IServiceReference.

    If you want the behavior of using Class2 with proxy support you will have to turn on CGLIB Read below:

    From Springs Doc:

    Spring AOP defaults to using standard J2SE dynamic proxies for AOP proxies. This enables any interface (or set of interfaces) to be proxied.

    Spring AOP can also use CGLIB proxies. This is necessary to proxy classes, rather than interfaces. CGLIB is used by default if a business object does not implement an interface. As it is good practice to program to interfaces rather than classes, business classes normally will implement one or more business interfaces. It is possible to force the use of CGLIB, in those (hopefully rare) cases where you need to advise a method that is not declared on an interface, or where you need to pass a proxied object to a method as a concrete type.

    It is important to grasp the fact that Spring AOP is proxy-based. See the section entitled Section 6.6.1, “Understanding AOP proxies” for a thorough examination of exactly what this implementation detail actually means.

提交回复
热议问题