Spring AOP CGLIB proxy's field is null

前端 未结 1 653
孤城傲影
孤城傲影 2020-12-20 14:24

Description

Using the vlcj component, the custom component appears as a result of the AOP proxy object null.

MediaList Class

public class         


        
相关标签:
1条回答
  • 2020-12-20 14:48

    This is a combination of potentially unexpected behaviors. First, Spring uses CGLIB to proxy your beans for AOP. CGLIB proxies are instances of a dynamic subtype of your class that delegate all method calls to a real instance of your class. However, even though the proxy is of a subtype, its fields are not initialized (ie. your TargetClass super constructor is not invoked). A lengthier explanation can be found here.

    Additionally, your method

    public final libvlc_media_list_t mediaListInstance() {
        return mediaListInstance; // <- proxy object return null, if use aop
    }
    

    or

    public final String test() {
        System.out.println("TargetClass.test();");
        return returnValue;
    }
    

    are final. CGLIB therefore cannot override them to delegate to the real instance. This would be hinted at in Spring logs. For example, you would see

    22:35:31.773 [main] INFO  o.s.aop.framework.CglibAopProxy - Unable to proxy method [public final java.lang.String com.example.root.TargetClass.test()] because it is final: All calls to this method via a proxy will NOT be routed to the target instance.
    

    Put all of the above together and you get a proxy instance where the field is null and where the proxy cannot delegate to the real instance's method. So your code will actually invoke

    public final String test() {
        System.out.println("TargetClass.test();");
        return returnValue;
    }
    

    for an instance where the returnValue field is null.


    If you can, change your method, remove the final modifier. If you can't, you'll have to rethink your design.

    0 讨论(0)
提交回复
热议问题