Casting a Spring's Proxy object to the actual runtime class

前端 未结 3 1593
夕颜
夕颜 2020-12-09 10:52

I\'m using Spring, at one point I would like to cast the object to its actual runtime implementation.

Example:

Class MyClass extends NotMyClass {
            


        
相关标签:
3条回答
  • 2020-12-09 11:32

    Now you can use

    AopTestUtils.getTargetObject(proxy)
    .

    The implementation is the same of @siulkilulki sugestion, but it's on Spring helper

    0 讨论(0)
  • 2020-12-09 11:35

    Basically when you use AOP in Spring, Spring build a Proxy for you. You have two option:

    1. when you apply an aspect on a bean that implements an interface, in this case Spring use JdkDynamicProxy
    2. when your spring bean don't implements any interface and if you have cglib 2.2 in you classpath, consider that from spring 3.2.x you have cglib in the spring container by default, spring use a special proxy called CGLibProxy.

    The key point here is that when an aspect is applied on your bean Spring will instance a proxy and if you try to perform a cast you will get an exception.

    I hope tha this can help you

    0 讨论(0)
  • 2020-12-09 11:57

    For me version from EDIT 2 didn't worked. Below one worked:

    @SuppressWarnings({"unchecked"})
    protected <T> T getTargetObject(Object proxy) throws Exception {
        while( (AopUtils.isJdkDynamicProxy(proxy))) {
            return (T) getTargetObject(((Advised)proxy).getTargetSource().getTarget());
        }
        return (T) proxy; // expected to be cglib proxy then, which is simply a specialized class
    }
    

    Usage:

        UserServicesImpl serviceImpl = getTargetObject(serviceProxy);
        serviceImpl.setUserDao(userDAO);
    
    0 讨论(0)
提交回复
热议问题